Skip to content
Back to search

ultimate_mcp_server

Comprehensive MCP server exposing dozens of capabilities to AI agents: multi-provider LLM delegation, browser automation, document processing, vector ops, and cognitive memory systems

Safety scan

A static text scan, not a guarantee. Select the badge to see what was scanned and every finding.

Checked today
Badge for your README
findsafeskills safety rating

Markdown

[![findsafeskills safety rating](/api/listings/dicklesworthstone--ultimate-mcp-server/badge.svg)](/listings/dicklesworthstone--ultimate-mcp-server)

HTML

<a href="/listings/dicklesworthstone--ultimate-mcp-server"><img src="/api/listings/dicklesworthstone--ultimate-mcp-server/badge.svg" alt="findsafeskills safety rating" /></a>

Install

i

Install instructions from the README

As written by the repo's author. findsafeskills has not verified these steps.

These steps run a script from the network that findsafeskills does not scan.

πŸ§ͺ Install

# Install uv (fast Python package manager) if you don't have it:
curl -LsSf https://astral.sh/uv/install.sh | sh

# Clone the repository
git clone https://github.com/Dicklesworthstone/ultimate_mcp_server.git
cd ultimate_mcp_server

# Create a virtual environment and install dependencies using uv:
uv venv --python 3.13
source .venv/bin/activate
uv lock --upgrade
uv sync --all-extras

*Note: The `uv sync --all-extras` command installs all optional extras defined in the project (e.g., OCR, Browser Automation, Excel). If you only need specific extras, adjust your project dependencies and run `uv sync` without `--all-extras`.*

βš™οΈ .env Configuration

Create a file named `.env` in the root directory of the cloned repository. Add your API keys and any desired configuration overrides:

# --- API Keys (at least one provider required) ---
OPENAI_API_KEY=your_openai_sk-...
ANTHROPIC_API_KEY=your_anthropic_sk-...
GEMINI_API_KEY=your_google_ai_studio_key... # For Google AI Studio (Gemini API)
# Or use GOOGLE_APPLICATION_CREDENTIALS=/path/to/your/service-account-key.json for Vertex AI
DEEPSEEK_API_KEY=your_deepseek_key...
OPENROUTER_API_KEY=your_openrouter_key...
GROK_API_KEY=your_grok_key... # For Grok via xAI API

# --- Local / Self-Hosted Providers (OpenAI-compatible, FREE inference) ---
# One generic provider covers Ollama, llama.cpp (llama-server), mistral.rs, vLLM, and LM Studio.
# No API key is required by most local servers; LOCAL_LLM_API_KEY is optional.
# LOCAL_LLM_BASE_URL=http://localhost:11434/v1   # Default (Ollama). Examples:
#   llama.cpp / mistral.rs / vLLM : http://localhost:8000/v1
#   LM Studio                     : http://localhost:1234/v1
# LOCAL_LLM_DEFAULT_MODEL=llama3.1:8b            # Model name as served by your local backend
# LOCAL_LLM_API_KEY=                             # Optional; most local servers ignore it
# LOCAL_LLM_REQUEST_TIMEOUT=30                   # Optional request timeout in seconds
# LOCAL_LLM_ENABLED=true                         # Optional; set false to disable the local provider

# --- Server Configuration (Defaults shown) ---
GATEWAY_SERVER_PORT=8013
GATEWAY_SERVER_HOST=127.0.0.1 # Change to 0.0.0.0 to listen on all interfaces (needed for Docker/external access)
# GATEWAY_API_PREFIX=/

# --- Logging Configuration (Defaults shown) ---
LOG_LEVEL=INFO # DEBUG, INFO, WARNING, ERROR, CRITICAL
USE_RICH_LOGGING=true # Set to false for plain text logs

# --- Cache Configuration (Defaults shown) ---
GATEWAY_CACHE_ENABLED=true
GATEWAY_CACHE_TTL=86400 # Default Time-To-Live in seconds (24 hours)
# GATEWAY_CACHE_TYPE=memory # Options might include 'memory', 'redis', 'diskcache' (check implementation)
# GATEWAY_CACHE_MAX_SIZE=1000 # Example: Max number of items for memory cache
# GATEWAY_CACHE_DIR=./.cache # Directory for disk cache storage

# --- Provider Timeouts & Retries (Defaults shown) ---
# GATEWAY_PROVIDER_TIMEOUT=120 # Default timeout in seconds for API calls
# GATEWAY_PROVIDER_MAX_RETRIES=3 # Default max retries on failure

# --- Provider-Specific Configuration ---
# GATEWAY_OPENAI_DEFAULT_MODEL=gpt-4.1-mini # Customize default model
# GATEWAY_ANTHROPIC_DEFAULT_MODEL=claude-3-5-sonnet-20241022 # Customize default model
# GATEWAY_GEMINI_DEFAULT_MODEL=gemini-2.0-pro # Customize default model

# --- Tool Specific Config (Examples) ---
# FILESYSTEM__ALLOWED_DIRECTORIES=["/path/to/safe/dir1","/path/to/safe/dir2"] # For Filesystem tools (JSON array)
# GATEWAY_AGENT_MEMORY_DB_PATH=unified_agent_memory.db # Path for agent memory database
# GATEWAY_PROMPT_TEMPLATES_DIR=./prompt_templates # Directory for prompt templates

▢️ Run

Make sure your virtual environment is active (`source .venv/bin/activate`).

# Start the MCP server with all registered tools found
umcp run

# Start the server including only specific tools
umcp run --include-tools completion chunk_document read_file write_file

# Start the server excluding specific tools

What was scanned

The files the safety scan read, as written by the repository's author and shown as plain text. Lines with a finding are marked.

README.md Β· README Β· 2,854 lines

View this file on GitHub (read at the repository's current version: the scan did not record which commit it read)

  1. # 🧠 Ultimate MCP Server
  2. <div align="center">
  3. [![Python 3.13+](https://img.shields.io/badge/python-3.13+-blue.svg)](https://www.python.org/downloads/)
  4. [![License: MIT](https://img.shields.io/badge/License-MIT%2BOpenAI%2FAnthropic%20Rider-blue.svg)](./LICENSE)
  5. [![MCP Protocol](https://img.shields.io/badge/Protocol-MCP-purple.svg)](https://github.com/modelcontextprotocol)
  6. ### A comprehensive Model Context Protocol (MCP) server providing advanced AI agents with dozens of powerful capabilities for cognitive augmentation, tool use, and intelligent orchestration
  7. <img src="https://raw.githubusercontent.com/Dicklesworthstone/ultimate_mcp_server/refs/heads/main/ultimate_mcp_banner.webp" alt="Illustration" width="600"/>
  8. **[Getting Started](#getting-started) β€’ [Key Features](#key-features) β€’ [Usage Examples](#usage-examples) β€’ [Architecture](#architecture)**
  9. </div>
  10. ---
  11. ## πŸ€– What is Ultimate MCP Server?
  12. **Ultimate MCP Server** is a comprehensive MCP-native system that serves as a complete AI agent operating system. It exposes dozens of powerful capabilities through the Model Context Protocol, enabling advanced AI agents to access a rich ecosystem of tools, cognitive systems, and specialized services.
  13. While it includes intelligent task delegation from sophisticated models (e.g., Claude 3.7 Sonnet) to cost-effective ones (e.g., Gemini Flash 2.0 Lite), this is just one facet of its extensive functionality. The server provides unified access to multiple LLM providers while optimizing for **cost**, **performance**, and **quality**.
  14. The system offers integrated cognitive memory systems, browser automation, Excel manipulation, database interactions, document processing, command-line utilities, dynamic API integration, OCR capabilities, vector operations, entity relation graphs, SQL database interactions, audio transcription, and much more. These capabilities transform an AI agent from a conversational interface into a powerful autonomous system capable of complex, multi-step operations across digital environments.
  15. <div align="center">
  16. <img src="https://raw.githubusercontent.com/Dicklesworthstone/ultimate_mcp_server/refs/heads/main/ultimate_mcp_logo.webp" alt="Illustration" width="600"/>
  17. </div>
  18. ---## 🎯 Vision: The Complete AI Agent Operating System
  19. At its core, Ultimate MCP Server represents a fundamental shift in how AI agents operate in digital environments. It serves as a comprehensive operating system for AI, providing:
  20. - 🧠 A unified cognitive architecture that enables persistent memory, reasoning, and contextual awareness
  21. - βš™οΈ Seamless access to dozens of specialized tools spanning web browsing, document processing, data analysis, and more
  22. - πŸ’» Direct system-level capabilities for filesystem operations, database interactions, and command-line utilities
  23. - πŸ”„ Dynamic workflow capabilities for complex multi-step task orchestration and execution
  24. - 🌐 Intelligent integration of various LLM providers with cost, quality, and performance optimization
  25. - πŸš€ Advanced vector operations, knowledge graphs, and retrieval-augmented generation for enhanced AI capabilities
  26. This approach mirrors how sophisticated operating systems provide applications with access to hardware, services, and resources - but designed specifically for augmenting AI agents with powerful new capabilities beyond their native abilities.
  27. ---
  28. ## πŸ”Œ MCP-Native Architecture
  29. The server is built entirely on the [Model Context Protocol (MCP)](https://github.com/modelcontextprotocol), making it specifically designed to work with AI agents like Claude. All functionality is exposed through standardized MCP tools that can be directly called by these agents, creating a seamless integration layer between AI agents and a comprehensive ecosystem of capabilities, services, and external systems.
  30. ---
  31. ## 🧬 Core Use Cases: AI Agent Augmentation and Ecosystem
  32. The Ultimate MCP Server transforms AI agents like Claude 3.7 Sonnet into autonomous systems capable of sophisticated operations across digital environments:
  33. ```plaintext
  34. interacts with
  35. β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” ────────────────────────► β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β” β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
  36. β”‚ Claude 3.7 β”‚ β”‚ Ultimate MCP β”‚ ───────►│ LLM Providersβ”‚
  37. β”‚ (Agent) β”‚ ◄──────────────────────── β”‚ Server β”‚ ◄───────│ External β”‚
  38. β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ returns results β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜ β”‚ Systems β”‚
  39. β”‚ β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
  40. β–Ό
  41. β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
  42. β”‚ Cognitive Memory Systems β”‚
  43. β”‚ Web & Data: Browser, DB, RAG, Vector Search β”‚
  44. β”‚ Documents: Excel, OCR, PDF, Filesystem β”‚
  45. β”‚ Analysis: Entity Graphs, Classification β”‚
  46. β”‚ Integration: APIs, CLI, Audio, Multimedia β”‚
  47. β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
  48. ```
  49. **Example workflow:**
  50. 1. An AI agent receives a complex task requiring multiple capabilities beyond its native abilities
  51. 2. The agent uses the Ultimate MCP Server to access specialized tools and services as needed
  52. 3. The agent can leverage the cognitive memory system to maintain state and context across operations
  53. 4. Complex tasks like research, data analysis, document creation, and multimedia processing become possible
  54. 5. The agent can orchestrate multi-step workflows combining various tools in sophisticated sequences
  55. 6. Results are returned in standard MCP format, enabling the agent to understand and work with them
  56. 7. One important benefit is cost optimization through delegating appropriate tasks to more efficient models
  57. This integration unlocks transformative capabilities that enable AI agents to autonomously complete complex projects while intelligently utilizing resources - including potentially saving 70-90% on API costs by using specialized tools and cost-effective models where appropriate.
  58. ---
  59. ## πŸ’‘ Why Use Ultimate MCP Server?
  60. ### 🧰 Comprehensive AI Agent Toolkit
  61. A unified hub enabling advanced AI agents to access an extensive ecosystem of tools:
  62. - 🌐 Perform complex web automation tasks (**Playwright** integration).
  63. - πŸ“Š Manipulate and analyze **Excel** spreadsheets with deep integration.
  64. - 🧠 Access rich **cognitive memory** systems for persistent agent state.
  65. - πŸ’Ύ Interact securely with the **filesystem**.
  66. - πŸ—„οΈ Interact with **databases** through SQL operations.
  67. - πŸ–ΌοΈ Process documents with **OCR** capabilities.
  68. - πŸ” Perform sophisticated **vector search** and **RAG** operations.
  69. - 🏷️ Utilize specialized **text processing** and **classification**.
  70. - ⌨️ Leverage command-line tools like **ripgrep**, **awk**, **sed**, **jq**.
  71. - πŸ”Œ Dynamically integrate external **REST APIs**.
  72. - ✨ Use **meta tools** for self-discovery, optimization, and documentation refinement.
  73. ### πŸ’΅ Cost Optimization
  74. API costs for advanced models can be substantial. Ultimate MCP Server helps reduce costs by:
  75. - πŸ“‰ Routing appropriate tasks to cheaper models (e.g., $0.01/1K tokens vs $0.15/1K tokens).
  76. - ⚑ Implementing **advanced caching** (exact, semantic, task-aware) to avoid redundant API calls.
  77. - πŸ’° Tracking and **optimizing costs** across providers.
  78. - 🧭 Enabling **cost-aware task routing** decisions.
  79. - πŸ› οΈ Handling routine processing with specialized non-LLM tools (filesystem, CLI utils, etc.).
  80. ### 🌐 Provider Abstraction
  81. Avoid provider lock-in with a unified interface:
  82. - πŸ”— Standard API for **OpenAI**, **Anthropic (Claude)**, **Google (Gemini)**, **xAI (Grok)**, **DeepSeek**, **OpenRouter**, and **local OpenAI-compatible servers** (Ollama, llama.cpp, mistral.rs, vLLM, LM Studio).
  83. - 🏠 **Free local inference**: a single configurable `local` provider talks to any OpenAI-compatible local server via `base_url`, and is accounted at **$0 cost** so the cost optimizer prefers it for delegated work.
  84. - βš™οΈ Consistent parameter handling and response formatting.
  85. - πŸ”„ Ability to **swap providers** without changing application code.
  86. - πŸ›‘οΈ Protection against provider-specific outages and limitations through fallback mechanisms.
  87. ### πŸ“‘ Comprehensive Document and Data Processing
  88. Process documents and data efficiently:
  89. - βœ‚οΈ Break documents into semantically meaningful **chunks**.
  90. - πŸš€ Process chunks in **parallel** across multiple models.
  91. - πŸ“Š Extract **structured data** (JSON, tables, key-value) from unstructured text.
  92. - ✍️ Generate **summaries** and insights from large texts.
  93. - πŸ” Convert formats (**HTML to Markdown**, documents to structured data).
  94. - πŸ‘οΈ Apply **OCR** to images and PDFs with optional LLM enhancement.
  95. ---
  96. ## πŸš€ Key Features
  97. ### πŸ”Œ MCP Protocol Integration
  98. - **Native MCP Server**: Built on the Model Context Protocol for seamless AI agent integration.
  99. - **MCP Tool Framework**: All functionality exposed through standardized MCP tools with clear schemas.
  100. - **Tool Composition**: Tools can be combined in workflows using dependencies.
  101. - **Tool Discovery**: Supports dynamic listing and capability discovery for agents.
  102. ### πŸ€– Intelligent Task Delegation
  103. - **Task Routing**: Analyzes tasks and routes to appropriate models or specialized tools.
  104. - **Provider Selection**: Chooses provider/model based on task requirements, cost, quality, or speed preferences.
  105. - **Cost-Performance Balancing**: Optimizes delegation strategy.
  106. - **Delegation Tracking**: Monitors delegation patterns, costs, and outcomes (via Analytics).
  107. ### 🌍 Provider Integration
  108. - **Multi-Provider Support**: First-class support for OpenAI, Anthropic, Google, DeepSeek, xAI (Grok), OpenRouter, and **local OpenAI-compatible servers** (Ollama, llama.cpp, mistral.rs, vLLM, LM Studio) via a single configurable `local` provider. Extensible architecture.
  109. - **Free Local Inference**: The `local` provider is cost-accounted at **$0**, so the intelligent delegation / cost-optimization layer will route cost-sensitive work (summarization, extraction, simple Q&A, formatting) to your own hardware when a capable local model is configured.
  110. - **Model Management**: Handles different model capabilities, context windows, and pricing. Automatic selection and fallback mechanisms.
  111. ### πŸ’Ύ Advanced Caching
  112. - **Multi-level Caching**: Exact match, semantic similarity, and task-aware strategies.
  113. - **Persistent Cache**: Disk-based persistence (e.g., DiskCache) with fast in-memory access layer.
  114. - **Cache Analytics**: Tracks cache hit rates, estimated cost savings.
  115. ### πŸ“„ Document Tools
  116. - **Smart Chunking**: Token-based, semantic boundary detection, structural analysis methods. Configurable overlap.
  117. - **Document Operations**: Summarization (paragraph, bullets), entity extraction, question generation, batch processing.
  118. ### πŸ“ Secure Filesystem Operations
  119. - **Path Management**: Robust validation, normalization, symlink security checks, configurable allowed directories.
  120. - **File Operations**: Read/write with encoding handling, smart text editing/replacement, metadata retrieval.
  121. - **Directory Operations**: Creation, listing, tree visualization, secure move/copy.
  122. - **Search Capabilities**: Recursive search with pattern matching and filtering.
  123. - **Security Focus**: Designed to prevent directory traversal and enforce boundaries.
  124. ### ✨ Autonomous Tool Documentation Refiner
  125. - **Automated Improvement**: Systematically analyzes, tests, and refines MCP tool documentation (docstrings, schemas, examples).
  126. - **Agent Simulation**: Identifies ambiguities from an LLM agent's perspective.
  127. - **Adaptive Testing**: Generates and executes schema-aware test cases.
  128. - **Failure Analysis**: Uses LLM ensembles to diagnose documentation weaknesses.
  129. - **Iterative Refinement**: Continuously improves documentation quality.
  130. - **(See dedicated section for more details)**
  131. ### 🌐 Browser Automation with Playwright
  132. - **Full Control**: Navigate, click, type, scrape data, screenshots, PDFs, file up/download, JS execution.
  133. - **Research**: Automate searches across engines, extract structured data, monitor sites.
  134. - **Synthesis**: Combine findings from multiple web sources into reports.
  135. ### 🧠 Cognitive & Agent Memory System
  136. - **Memory Hierarchy**: Working, episodic, semantic, procedural levels.
  137. - **Knowledge Management**: Store/retrieve memories with metadata, relationships, importance tracking.
  138. - **Workflow Tracking**: Record agent actions, reasoning chains, artifacts, dependencies.
  139. - **Smart Operations**: Memory consolidation, reflection generation, relevance-based optimization, decay.
  140. ### πŸ“Š Excel Spreadsheet Automation
  141. - **Direct Manipulation**: Create, modify, format Excel files via natural language or structured instructions. Analyze formulas.
  142. - **Template Learning**: Learn from examples, adapt templates, apply formatting patterns.
  143. - **VBA Macro Generation**: Generate VBA code from instructions for complex automation.
  144. ### πŸ—οΈ Structured Data Extraction
  145. - **JSON Extraction**: Extract structured JSON with schema validation.
  146. - **Table Extraction**: Extract tables in multiple formats (JSON, CSV, Markdown).
  147. - **Key-Value Extraction**: Simple K/V pair extraction.
  148. - **Semantic Schema Inference**: Attempt to generate schemas from text.
  149. ### βš”οΈ Tournament Mode
  150. - **Model Competitions**: Run head-to-head comparisons for code or text generation tasks.
  151. - **Multi-Model Evaluation**: Compare outputs from different models/providers simultaneously.
  152. - **Performance Metrics**: Evaluate correctness, efficiency, style, etc. Persist results.
  153. ### πŸ—„οΈ SQL Database Interactions
  154. - **Query Execution**: Run SQL queries against various DB types (SQLite, PostgreSQL, etc. via SQLAlchemy).
  155. - **Schema Analysis**: Analyze schemas, suggest optimizations (using LLM).
  156. - **Data Exploration**: Browse tables, visualize contents.
  157. - **Query Generation**: Generate SQL from natural language descriptions.
  158. ### πŸ”— Entity Relation Graphs
  159. - **Entity Extraction**: Identify entities (people, orgs, locations, etc.).
  160. - **Relationship Mapping**: Discover and map connections between entities.
  161. - **Knowledge Graph Construction**: Build persistent graphs (e.g., using NetworkX).
  162. - **Graph Querying**: Extract insights using graph traversal or LLM-based queries.
  163. ### πŸ”Ž Advanced Vector Operations
  164. - **Semantic Search**: Find similar content using vector embeddings.
  165. - **Vector Storage Integration**: Interfaces with vector databases or local stores.
  166. - **Hybrid Search**: Combines keyword and semantic search (e.g., via Marqo integration).
  167. - **Batched Processing**: Efficient embedding generation and searching for large datasets.
  168. ### πŸ“š Retrieval-Augmented Generation (RAG)
  169. - **Contextual Generation**: Augments prompts with relevant retrieved documents/chunks.
  170. - **Accuracy Improvement**: Reduces hallucinations by grounding responses in provided context.
  171. - **Workflow Integration**: Seamlessly combines retrieval (vector/keyword search) with generation. Customizable strategies.
  172. ### πŸŽ™οΈ Audio Transcription
  173. - **Speech-to-Text**: Convert audio files (e.g., WAV, MP3) to text using models like Whisper.
  174. - **Speaker Diarization**: Identify different speakers (if supported by the model/library).
  175. - **Transcript Enhancement**: Clean and format transcripts using LLMs.
  176. - **Multi-language Support**: Handles various languages based on the underlying transcription model.
  177. ### 🏷️ Text Classification
  178. - **Custom Classifiers**: Apply text classification models (potentially fine-tuned or using zero-shot LLMs).
  179. - **Multi-label Classification**: Assign multiple categories.
  180. - **Confidence Scoring**: Provide probabilities for classifications.
  181. - **Batch Processing**: Classify large document sets efficiently.
  182. ### πŸ‘οΈ OCR Tools
  183. - **PDF/Image Extraction**: Uses Tesseract or other OCR engines, enhanced with LLM correction/formatting.
  184. - **Preprocessing**: Image denoising, thresholding, deskewing options.
  185. - **Structure Analysis**: Extracts PDF metadata and structure.
  186. - **Batch Processing**: Handles multiple files concurrently.
  187. - **(Requires `ocr` extra dependencies: `uv pip install -e ".[ocr]"`)**
  188. ### πŸ“ Text Redline Tools
  189. - **HTML Redline Generation**: Visual diffs (insertions, deletions, moves) between text/HTML. Standalone HTML output.
  190. - **Document Comparison**: Compares various formats with intuitive highlighting.
  191. ### πŸ”„ HTML to Markdown Conversion
  192. - **Intelligent Conversion**: Detects content type, uses libraries like `readability-lxml`, `trafilatura`, `markdownify`.
  193. - **Content Extraction**: Filters boilerplate, preserves structure (tables, links).
  194. - **Markdown Optimization**: Cleans and normalizes output.
  195. ### πŸ“ˆ Workflow Optimization Tools
  196. - **Cost Estimation/Comparison**: Pre-execution cost estimates, model cost comparisons.
  197. - **Model Selection Guidance**: Recommends models based on task, budget, performance needs.
  198. - **Workflow Execution Engine**: Runs multi-stage pipelines with dependencies, parallel execution, variable passing.
  199. ### πŸ’» Local Text Processing Tools (CLI Integration)
  200. - **Offline Power**: Securely wrap and expose command-line tools like `ripgrep` (fast regex search), `awk` (text processing), `sed` (stream editor), `jq` (JSON processing) as MCP tools. Process text locally without API calls.
  201. ### ⏱️ Model Performance Benchmarking
  202. - **Empirical Measurement**: Tools to measure actual speed (tokens/sec), latency across providers/models.
  203. - **Performance Profiles**: Generate comparative reports based on real-world performance.
  204. - **Data-Driven Optimization**: Use benchmark data to inform routing decisions.
  205. ### πŸ“‘ Multiple Transport Modes
  206. - **Streamable-HTTP (Recommended)**: Modern HTTP transport with streaming request/response bodies, optimal for HTTP-based MCP clients.
  207. - **Server-Sent Events (SSE)**: Legacy HTTP transport using server-sent events for real-time streaming.
  208. - **Standard I/O (stdio)**: Direct process communication for embedded integrations.
  209. - **Real-time Streaming**: Token-by-token updates for LLM completions across all HTTP transports.
  210. - **Progress Monitoring**: Track progress of long-running jobs (chunking, batch processing).
  211. - **Event-Based Architecture**: Subscribe to specific server events.
  212. ### ✨ Multi-Model Synthesis
  213. - **Comparative Analysis**: Analyze outputs from multiple models side-by-side.
  214. - **Response Synthesis**: Combine best elements, generate meta-responses, create consensus outputs.
  215. - **Collaborative Reasoning**: Implement workflows where different models handle different steps.
  216. ### 🧩 Extended Model Support
  217. - **Grok Integration**: Native support for xAI's Grok.
  218. - **DeepSeek Support**: Optimized handling for DeepSeek models.
  219. - **OpenRouter Integration**: Access a wide variety via OpenRouter API key.
  220. - **Local / Self-Hosted Integration**: A single configurable `local` provider for any OpenAI-compatible local server β€” Ollama, llama.cpp's `llama-server`, mistral.rs, vLLM, and LM Studio β€” point it at a `base_url` and run **free** ($0-cost) inference on your own hardware.
  221. - **Gemini Integration**: Comprehensive support for Google's Gemini models.
  222. - **Anthropic Integration**: Full support for Claude models including Claude 3.5 Sonnet and Haiku.
  223. - **OpenAI Integration**: Complete support for GPT-3.5, GPT-4.0, and newer models.
  224. ### πŸ”§ Meta Tools for Self-Improvement & Dynamic Integration
  225. - **Tool Discovery**: Agents can query available tools, parameters, descriptions (`list_tools`).
  226. - **Usage Recommendations**: Get AI-driven advice on tool selection/combination for tasks.
  227. - **External API Integration**: Dynamically register REST APIs via OpenAPI specs, making endpoints available as callable MCP tools (`register_api`, `call_dynamic_tool`).
  228. - **Documentation Generation**: Part of the Autonomous Refiner feature.
  229. ### πŸ“Š Analytics and Reporting
  230. - **Usage Tracking**: Monitors tokens, costs, requests, success/error rates per provider/model/tool.
  231. - **Real-Time Monitoring**: Live dashboard or stream of usage stats.
  232. - **Detailed Reporting**: Generate historical cost/usage reports, identify trends, export data.
  233. - **Optimization Insights**: Helps identify expensive operations or inefficient patterns.
  234. ### πŸ“œ Prompt Templates and Management
  235. - **Jinja2 Templates**: Create reusable, dynamic prompts with variables, conditionals, includes.
  236. - **Prompt Repository**: Store, retrieve, categorize, and version control prompts.
  237. - **Metadata**: Add descriptions, authorship, usage examples to templates.
  238. - **Optimization**: Test and compare template performance and token usage.
  239. ### πŸ›‘οΈ Error Handling and Resilience
  240. - **Intelligent Retries**: Automatic retries with exponential backoff for transient errors (rate limits, network issues).
  241. - **Fallback Mechanisms**: Configurable provider fallbacks on primary failure.
  242. - **Detailed Error Reporting**: Captures comprehensive error context for debugging.
  243. - **Input Validation**: Pre-flight checks for common issues (e.g., token limits, required parameters).
  244. ### βš™οΈ System Features
  245. - **Rich Logging**: Colorful, informative console logs via `Rich`.
  246. - **Health Monitoring**: `/healthz` endpoint for readiness checks.
  247. - **Command-Line Interface**: `umcp` CLI for management and interaction.
  248. ---
  249. ## πŸ“¦ Getting Started
  250. ### πŸ§ͺ Install
  251. ```bash
  252. # Install uv (fast Python package manager) if you don't have it:
  253. curl -LsSf https://astral.sh/uv/install.sh | sh
  254. # Clone the repository
  255. git clone https://github.com/Dicklesworthstone/ultimate_mcp_server.git
  256. cd ultimate_mcp_server
  257. # Create a virtual environment and install dependencies using uv:
  258. uv venv --python 3.13
  259. source .venv/bin/activate
  260. uv lock --upgrade
  261. uv sync --all-extras
  262. ```
  263. *Note: The `uv sync --all-extras` command installs all optional extras defined in the project (e.g., OCR, Browser Automation, Excel). If you only need specific extras, adjust your project dependencies and run `uv sync` without `--all-extras`.*
  264. ### βš™οΈ .env Configuration
  265. Create a file named `.env` in the root directory of the cloned repository. Add your API keys and any desired configuration overrides:
  266. ```bash
  267. # --- API Keys (at least one provider required) ---
  268. OPENAI_API_KEY=your_openai_sk-...
  269. ANTHROPIC_API_KEY=your_anthropic_sk-...
  270. GEMINI_API_KEY=your_google_ai_studio_key... # For Google AI Studio (Gemini API)
  271. # Or use GOOGLE_APPLICATION_CREDENTIALS=/path/to/your/service-account-key.json for Vertex AI
  272. DEEPSEEK_API_KEY=your_deepseek_key...
  273. OPENROUTER_API_KEY=your_openrouter_key...
  274. GROK_API_KEY=your_grok_key... # For Grok via xAI API
  275. # --- Local / Self-Hosted Providers (OpenAI-compatible, FREE inference) ---
  276. # One generic provider covers Ollama, llama.cpp (llama-server), mistral.rs, vLLM, and LM Studio.
  277. # No API key is required by most local servers; LOCAL_LLM_API_KEY is optional.
  278. # LOCAL_LLM_BASE_URL=http://localhost:11434/v1 # Default (Ollama). Examples:
  279. # llama.cpp / mistral.rs / vLLM : http://localhost:8000/v1
  280. # LM Studio : http://localhost:1234/v1
  281. # LOCAL_LLM_DEFAULT_MODEL=llama3.1:8b # Model name as served by your local backend
  282. # LOCAL_LLM_API_KEY= # Optional; most local servers ignore it
  283. # LOCAL_LLM_REQUEST_TIMEOUT=30 # Optional request timeout in seconds
  284. # LOCAL_LLM_ENABLED=true # Optional; set false to disable the local provider
  285. # --- Server Configuration (Defaults shown) ---
  286. GATEWAY_SERVER_PORT=8013
  287. GATEWAY_SERVER_HOST=127.0.0.1 # Change to 0.0.0.0 to listen on all interfaces (needed for Docker/external access)
  288. # GATEWAY_API_PREFIX=/
  289. # --- Logging Configuration (Defaults shown) ---
  290. LOG_LEVEL=INFO # DEBUG, INFO, WARNING, ERROR, CRITICAL
  291. USE_RICH_LOGGING=true # Set to false for plain text logs
  292. # --- Cache Configuration (Defaults shown) ---
  293. GATEWAY_CACHE_ENABLED=true
  294. GATEWAY_CACHE_TTL=86400 # Default Time-To-Live in seconds (24 hours)
  295. # GATEWAY_CACHE_TYPE=memory # Options might include 'memory', 'redis', 'diskcache' (check implementation)
  296. # GATEWAY_CACHE_MAX_SIZE=1000 # Example: Max number of items for memory cache
  297. # GATEWAY_CACHE_DIR=./.cache # Directory for disk cache storage
  298. # --- Provider Timeouts & Retries (Defaults shown) ---
  299. # GATEWAY_PROVIDER_TIMEOUT=120 # Default timeout in seconds for API calls
  300. # GATEWAY_PROVIDER_MAX_RETRIES=3 # Default max retries on failure
  301. # --- Provider-Specific Configuration ---
  302. # GATEWAY_OPENAI_DEFAULT_MODEL=gpt-4.1-mini # Customize default model
  303. # GATEWAY_ANTHROPIC_DEFAULT_MODEL=claude-3-5-sonnet-20241022 # Customize default model
  304. # GATEWAY_GEMINI_DEFAULT_MODEL=gemini-2.0-pro # Customize default model
  305. # --- Tool Specific Config (Examples) ---
  306. # FILESYSTEM__ALLOWED_DIRECTORIES=["/path/to/safe/dir1","/path/to/safe/dir2"] # For Filesystem tools (JSON array)
  307. # GATEWAY_AGENT_MEMORY_DB_PATH=unified_agent_memory.db # Path for agent memory database
  308. # GATEWAY_PROMPT_TEMPLATES_DIR=./prompt_templates # Directory for prompt templates
  309. ```
  310. ### ▢️ Run
  311. Make sure your virtual environment is active (`source .venv/bin/activate`).
  312. ```bash
  313. # Start the MCP server with all registered tools found
  314. umcp run
  315. # Start the server including only specific tools
  316. umcp run --include-tools completion chunk_document read_file write_file
  317. # Start the server excluding specific tools
  318. umcp run --exclude-tools browser_init browser_navigate research_and_synthesize_report
  319. # Start with Docker (ensure .env file exists in the project root or pass environment variables)
  320. docker compose up --build # Add --build the first time or after changes
  321. ```
  322. Once running, the server will typically be available at `http://localhost:8013` (or the host/port configured in your `.env` or command line). You should see log output indicating the server has started and which tools are registered.
  323. ## πŸ’» Command Line Interface (CLI)
  324. The Ultimate MCP Server provides a powerful command-line interface (CLI) through the `umcp` command that allows you to manage the server, interact with LLM providers, test features, and explore examples. This section details all available commands and their options.
  325. ### 🌟 Global Options
  326. The `umcp` command supports the following global option:
  327. ```bash
  328. umcp --version # Display version information
  329. ```
  330. ### πŸš€ Server Management
  331. #### Starting the Server
  332. The `run` command starts the Ultimate MCP Server with specified options:
  333. ```bash
  334. # Basic server start with default settings from .env
  335. umcp run
  336. # Run on a specific host (-h) and port (-p)
  337. umcp run -h 0.0.0.0 -p 9000
  338. # Run with multiple worker processes (-w)
  339. umcp run -w 4
  340. # Enable debug logging (-d)
  341. umcp run -d
  342. # Use stdio transport (-t)
  343. umcp run -t stdio
  344. # Use streamable-http transport (recommended for HTTP clients)
  345. umcp run -t shttp
  346. # Run only with specific tools (no shortcut for --include-tools)
  347. umcp run --include-tools completion chunk_document read_file write_file
  348. # Run with all tools except certain ones (no shortcut for --exclude-tools)
  349. umcp run --exclude-tools browser_init browser_navigate
  350. ```
  351. Example output:
  352. ```
  353. β”Œβ”€ Starting Ultimate MCP Server ───────────────────┐
  354. β”‚ Host: 0.0.0.0 β”‚
  355. β”‚ Port: 9000 β”‚
  356. β”‚ Workers: 4 β”‚
  357. β”‚ Transport mode: streamable-http β”‚
  358. β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
  359. INFO: Started server process [12345]
  360. INFO: Waiting for application startup.
  361. INFO: Application startup complete.
  362. INFO: Uvicorn running on http://0.0.0.0:9000 (Press CTRL+C to quit)
  363. ```
  364. Available options:
  365. - `-h, --host`: Host or IP address to bind the server to (default: from .env)
  366. - `-p, --port`: Port to listen on (default: from .env)
  367. - `-w, --workers`: Number of worker processes to spawn (default: from .env)
  368. - `-t, --transport-mode`: Transport mode for server communication ('shttp' for streamable-http, 'sse', or 'stdio', default: shttp)
  369. - `-d, --debug`: Enable debug logging
  370. - `--include-tools`: List of tool names to include (comma-separated)
  371. - `--exclude-tools`: List of tool names to exclude (comma-separated)
  372. ### πŸ”Œ Provider Management
  373. #### Listing Providers
  374. The `providers` command displays information about configured LLM providers:
  375. ```bash
  376. # List all configured providers
  377. umcp providers
  378. # Check API keys (-c) for all configured providers
  379. umcp providers -c
  380. # List available models (no shortcut for --models)
  381. umcp providers --models
  382. # Check keys and list models
  383. umcp providers -c --models
  384. ```
  385. Example output:
  386. ```
  387. β”Œβ”€ LLM Providers ──────────────────────────────────────────────────┐
  388. β”‚ Provider Status Default Model API Key β”‚
  389. β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
  390. β”‚ openai βœ“ gpt-4.1-mini sk-...5vX [VALID] β”‚
  391. β”‚ anthropic βœ“ claude-3-5-sonnet-20241022 sk-...Hr [VALID] β”‚
  392. β”‚ gemini βœ“ gemini-2.0-pro [VALID] β”‚
  393. β”‚ deepseek βœ— deepseek-chat [NOT CONFIGURED] β”‚
  394. β”‚ openrouter βœ“ -- [VALID] β”‚
  395. β”‚ grok βœ“ grok-1 [VALID] β”‚
  396. β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
  397. ```
  398. With `--models`:
  399. ```
  400. OPENAI MODELS:
  401. - gpt-4.1-mini
  402. - gpt-4o
  403. - gpt-4-0125-preview
  404. - gpt-3.5-turbo
  405. ANTHROPIC MODELS:
  406. - claude-3-5-sonnet-20241022
  407. - claude-3-5-haiku-20241022
  408. - claude-3-opus-20240229
  409. ...
  410. ```
  411. Available options:
  412. - `-c, --check`: Check API keys for all configured providers
  413. - `--models`: List available models for each provider
  414. #### Testing a Provider
  415. The `test` command allows you to test a specific provider:
  416. ```bash
  417. # Test the default OpenAI model with a simple prompt
  418. umcp test openai
  419. # Test a specific model (--model) with a custom prompt (--prompt)
  420. umcp test anthropic --model claude-3-5-haiku-20241022 --prompt "Write a short poem about coding."
  421. # Test Gemini with a different prompt
  422. umcp test gemini --prompt "What are three interesting AI research papers from 2024?"
  423. ```
  424. Example output:
  425. ```
  426. Testing provider 'anthropic'...
  427. Provider: anthropic
  428. Model: claude-3-5-haiku-20241022
  429. Prompt: Write a short poem about coding.
  430. ❯ Response:
  431. Code flows like water,
  432. Logic cascades through the mindβ€”
  433. Bugs bloom like flowers.
  434. Tokens: 13 input, 19 output
  435. Cost: $0.00006
  436. Response time: 0.82s
  437. ```
  438. Available options:
  439. - `--model`: Model ID to test (defaults to the provider's default)
  440. - `--prompt`: Prompt text to send (default: "Hello, world!")
  441. ### ⚑ Direct Text Generation
  442. The `complete` command lets you generate text directly from the CLI:
  443. ```bash
  444. # Generate text with default provider (OpenAI) using a prompt (--prompt)
  445. umcp complete --prompt "Write a concise explanation of quantum computing."
  446. # Specify a provider (--provider) and model (--model)
  447. umcp complete --provider anthropic --model claude-3-5-sonnet-20241022 --prompt "What are the key differences between Rust and Go?"
  448. # Use a system prompt (--system)
  449. umcp complete --provider openai --model gpt-4o --system "You are an expert programmer..." --prompt "Explain dependency injection."
  450. # Stream the response token by token (-s)
  451. umcp complete --provider openai --prompt "Count from 1 to 10." -s
  452. # Adjust temperature (--temperature) and token limit (--max-tokens)
  453. umcp complete --provider gemini --temperature 1.2 --max-tokens 250 --prompt "Generate a creative sci-fi story opening."
  454. # Read prompt from stdin (no --prompt needed)
  455. echo "Tell me about space exploration." | umcp complete
  456. ```
  457. Example output:
  458. ```
  459. Quantum computing uses quantum bits (qubits) that can exist in multiple states simultaneously, unlike classical bits (0 or 1). This quantum superposition, along with entanglement, allows quantum computers to process vast amounts of information in parallel, potentially solving certain complex problems exponentially faster than classical computers. Applications include cryptography, materials science, and optimization problems.
  460. Tokens: 13 input, 72 output
  461. Cost: $0.00006
  462. Response time: 0.37s
  463. ```
  464. Available options:
  465. - `--provider`: Provider to use (default: openai)
  466. - `--model`: Model ID (defaults to provider's default)
  467. - `--prompt`: Prompt text (reads from stdin if not provided)
  468. - `--temperature`: Sampling temperature (0.0-2.0, default: 0.7)
  469. - `--max-tokens`: Maximum tokens to generate
  470. - `--system`: System prompt for providers that support it
  471. - `-s, --stream`: Stream the response token by token
  472. ### πŸ’Ύ Cache Management
  473. The `cache` command allows you to view or clear the request cache:
  474. ```bash
  475. # Show cache status (default action)
  476. umcp cache
  477. # Explicitly show status (no shortcut for --status)
  478. umcp cache --status
  479. # Clear the cache (no shortcut for --clear, with confirmation prompt)
  480. umcp cache --clear
  481. # Show stats and clear the cache in one command
  482. umcp cache --status --clear
  483. ```
  484. Example output:
  485. ```
  486. Cache Status:
  487. Backend: memory
  488. Enabled: True
  489. Items: 127
  490. Hit rate: 73.2%
  491. Estimated savings: $1.47
  492. ```
  493. Available options:
  494. - `--status`: Show cache status (enabled by default if no other flag)
  495. - `--clear`: Clear the cache (will prompt for confirmation)
  496. ### πŸ“Š Benchmarking
  497. The `benchmark` command lets you compare performance and cost across providers:
  498. ```bash
  499. # Run default benchmark (3 runs per provider)
  500. umcp benchmark
  501. # Benchmark only specific providers
  502. umcp benchmark --providers openai,anthropic
  503. # Benchmark with specific models
  504. umcp benchmark --providers openai,anthropic --models gpt-4o,claude-3.5-sonnet
  505. # Use a custom prompt and more runs (-r)
  506. umcp benchmark --prompt "Explain the process of photosynthesis in detail." -r 5
  507. ```
  508. Example output:
  509. ```
  510. β”Œβ”€ Benchmark Results ───────────────────────────────────────────────────────┐
  511. β”‚ Provider Model Avg Time Tokens Cost Tokens/sec β”‚
  512. β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
  513. β”‚ openai gpt-4.1-mini 0.47s 76 / 213 $0.00023 454 β”‚
  514. β”‚ anthropic claude-3-5-haiku 0.52s 76 / 186 $0.00012 358 β”‚
  515. β”‚ gemini gemini-2.0-pro 0.64s 76 / 201 $0.00010 314 β”‚
  516. β”‚ deepseek deepseek-chat 0.71s 76 / 195 $0.00006 275 β”‚
  517. β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
  518. ```
  519. Available options:
  520. - `--providers`: List of providers to benchmark (default: all configured)
  521. - `--models`: Model IDs to benchmark (defaults to default model of each provider)
  522. - `--prompt`: Prompt text to use (default: built-in benchmark prompt)
  523. - `-r, --runs`: Number of runs per provider/model (default: 3)
  524. ### 🧰 Tool Management
  525. The `tools` command lists available tools, optionally filtered by category:
  526. ```bash
  527. # List all tools
  528. umcp tools
  529. # List tools in a specific category
  530. umcp tools --category document
  531. # Show related example scripts
  532. umcp tools --examples
  533. ```
  534. Example output:
  535. ```
  536. β”Œβ”€ Ultimate MCP Server Tools ─────────────────────────────────────────┐
  537. β”‚ Category Tool Example Script β”‚
  538. β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
  539. β”‚ completion generate_completion simple_completion_demo.py β”‚
  540. β”‚ completion stream_completion simple_completion_demo.py β”‚
  541. β”‚ completion chat_completion claude_integration_demo.pyβ”‚
  542. β”‚ document summarize_document document_processing.py β”‚
  543. β”‚ document chunk_document document_processing.py β”‚
  544. β”‚ extraction extract_json advanced_extraction_demo.pyβ”‚
  545. β”‚ filesystem read_file filesystem_operations_demo.pyβ”‚
  546. β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
  547. Tip: Run examples using the command:
  548. umcp examples <example_name>
  549. ```
  550. Available options:
  551. - `--category`: Filter tools by category
  552. - `--examples`: Show example scripts alongside tools
  553. ### πŸ“š Example Management
  554. The `examples` command lets you list and run example scripts:
  555. ```bash
  556. # List all example scripts (default action)
  557. umcp examples
  558. # Explicitly list example scripts (-l)
  559. umcp examples -l
  560. # Run a specific example
  561. umcp examples rag_example.py
  562. # Can also run by just the name without extension
  563. umcp examples rag_example
  564. ```
  565. Example output when listing:
  566. ```
  567. β”Œβ”€ Ultimate MCP Server Example Scripts ─────────────────────────────────┐
  568. β”‚ Category Example Script β”‚
  569. β”œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€
  570. β”‚ text-generation simple_completion_demo.py β”‚
  571. β”‚ text-generation claude_integration_demo.py β”‚
  572. β”‚ document-processing document_processing.py β”‚
  573. β”‚ search-and-retrieval rag_example.py β”‚
  574. β”‚ browser-automation browser_automation_demo.py β”‚
  575. β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
  576. Run an example:
  577. umcp examples <example_name>
  578. ```
  579. When running an example:
  580. ```
  581. Running example: rag_example.py
  582. Creating vector knowledge base 'demo_kb'...
  583. Adding sample documents...
  584. Retrieving context for query: "What are the benefits of clean energy?"
  585. Generated response:
  586. Based on the retrieved context, clean energy offers several benefits:
  587. ...
  588. ```
  589. Available options:
  590. - `-l, --list`: List example scripts only
  591. - `--category`: Filter examples by category
  592. ### πŸ”Ž Getting Help
  593. Every command has detailed help available:
  594. ```bash
  595. # General help
  596. umcp --help
  597. # Help for a specific command
  598. umcp run --help
  599. umcp providers --help
  600. umcp complete --help
  601. ```
  602. Example output:
  603. ```
  604. Usage: umcp [OPTIONS] COMMAND [ARGS]...
  605. Ultimate MCP Server: Multi-provider LLM management server
  606. Unified CLI to run your server, manage providers, and more.
  607. Options:
  608. --version, -v Show the application version and exit.
  609. --help Show this message and exit.
  610. Commands:
  611. run Run the Ultimate MCP Server
  612. providers List Available Providers
  613. test Test a Specific Provider
  614. complete Generate Text Completion
  615. cache Cache Management
  616. benchmark Benchmark Providers
  617. tools List Available Tools
  618. examples Run or List Example Scripts
  619. ```
  620. Command-specific help:
  621. ```
  622. Usage: umcp run [OPTIONS]
  623. Run the Ultimate MCP Server
  624. Start the server with optional overrides.
  625. Examples:
  626. umcp run -h 0.0.0.0 -p 8000 -w 4 -t sse
  627. umcp run -d
  628. Options:
  629. -h, --host TEXT Host or IP address to bind the server to.
  630. Defaults from config.
  631. -p, --port INTEGER Port to listen on. Defaults from config.
  632. -w, --workers INTEGER Number of worker processes to spawn.
  633. Defaults from config.
  634. -t, --transport-mode [shttp|sse|stdio]
  635. Transport mode for server communication (-t
  636. shortcut). Options: 'shttp' (streamable-http,
  637. recommended), 'sse', or 'stdio'.
  638. -d, --debug Enable debug logging for detailed output (-d
  639. shortcut).
  640. --include-tools TEXT List of tool names to include when running
  641. the server.
  642. --exclude-tools TEXT List of tool names to exclude when running
  643. the server.
  644. --help Show this message and exit.
  645. ```
  646. ---
  647. ## πŸ§ͺ Usage Examples
  648. This section provides Python examples demonstrating how an MCP client (like an application using `mcp-client` or an agent like Claude) would interact with the tools provided by a running Ultimate MCP Server instance.
  649. *Note: These examples assume you have `mcp-client` installed (`pip install mcp-client`) and the Ultimate MCP Server is running at `http://localhost:8013`.*
  650. *(The detailed code blocks from the original input are preserved below for completeness)*
  651. ### Basic Completion
  652. ```python
  653. import asyncio
  654. from mcp.client import Client
  655. async def basic_completion_example():
  656. client = Client("http://localhost:8013")
  657. response = await client.tools.completion(
  658. prompt="Write a short poem about a robot learning to dream.",
  659. provider="openai",
  660. model="gpt-4.1-mini",
  661. max_tokens=100,
  662. temperature=0.7
  663. )
  664. if response["success"]:
  665. print(f"Completion: {response['completion']}")
  666. print(f"Cost: ${response['cost']:.6f}")
  667. else:
  668. print(f"Error: {response['error']}")
  669. await client.close()
  670. # if __name__ == "__main__": asyncio.run(basic_completion_example())
  671. ```
  672. ### Claude Using Ultimate MCP Server for Document Analysis (Delegation)
  673. ```python
  674. import asyncio
  675. from mcp.client import Client
  676. async def document_analysis_example():
  677. # Assume Claude identifies a large document needing processing
  678. client = Client("http://localhost:8013")
  679. document = "... large document content ..." * 100 # Placeholder for large content
  680. print("Delegating document chunking...")
  681. # Step 1: Claude delegates document chunking (often a local, non-LLM task on server)
  682. chunks_response = await client.tools.chunk_document(
  683. document=document,
  684. chunk_size=1000, # Target tokens per chunk
  685. overlap=100, # Token overlap
  686. method="semantic" # Use semantic chunking if available
  687. )
  688. if not chunks_response["success"]:
  689. print(f"Chunking failed: {chunks_response['error']}")
  690. await client.close()
  691. return
  692. print(f"Document divided into {chunks_response['chunk_count']} chunks.")
  693. # Step 2: Claude delegates summarization of each chunk to a cheaper model
  694. summaries = []
  695. total_cost = 0.0
  696. print("Delegating chunk summarization to gemini-2.0-flash-lite...")
  697. for i, chunk in enumerate(chunks_response["chunks"]):
  698. # Use Gemini Flash (much cheaper than Claude or GPT-4o) via the server
  699. summary_response = await client.tools.summarize_document(
  700. document=chunk,
  701. provider="gemini", # Explicitly delegate to Gemini via server
  702. model="gemini-2.0-flash-lite",
  703. format="paragraph",
  704. max_length=150 # Request a concise summary
  705. )
  706. if summary_response["success"]:
  707. summaries.append(summary_response["summary"])
  708. cost = summary_response.get("cost", 0.0)
  709. total_cost += cost
  710. print(f" Processed chunk {i+1}/{chunks_response['chunk_count']} summary. Cost: ${cost:.6f}")
  711. else:
  712. print(f" Chunk {i+1} summarization failed: {summary_response['error']}")
  713. print("\nDelegating entity extraction to gpt-4.1-mini...")
  714. # Step 3: Claude delegates entity extraction for the whole document to another cheap model
  715. entities_response = await client.tools.extract_entities(
  716. document=document, # Process the original document
  717. entity_types=["person", "organization", "location", "date", "product"],
  718. provider="openai", # Delegate to OpenAI's cheaper model
  719. model="gpt-4.1-mini"
  720. )
  721. if entities_response["success"]:
  722. cost = entities_response.get("cost", 0.0)
  723. total_cost += cost
  724. print(f"Extracted entities. Cost: ${cost:.6f}")
  725. extracted_entities = entities_response['entities']
  726. # Claude would now process these summaries and entities using its advanced capabilities
  727. print(f"\nClaude can now use {len(summaries)} summaries and {len(extracted_entities)} entity groups.")
  728. else:
  729. print(f"Entity extraction failed: {entities_response['error']}")
  730. print(f"\nTotal estimated delegation cost for sub-tasks: ${total_cost:.6f}")
  731. # Claude might perform final synthesis using the collected results
  732. final_synthesis_prompt = f"""
  733. Synthesize the key information from the following summaries and entities extracted from a large document.
  734. Focus on the main topics, key people involved, and significant events mentioned.
  735. Summaries:
  736. {' '.join(summaries)}
  737. Entities:
  738. {extracted_entities}
  739. Provide a concise final report.
  740. """
  741. # This final step would likely use Claude itself (not shown here)
  742. await client.close()
  743. # if __name__ == "__main__": asyncio.run(document_analysis_example())
  744. ```
  745. ### Browser Automation for Research
  746. ```python
  747. import asyncio
  748. from mcp.client import Client
  749. async def browser_research_example():
  750. client = Client("http://localhost:8013")
  751. print("Starting browser-based research task...")
  752. # This tool likely orchestrates multiple browser actions (search, navigate, scrape)
  753. # and uses an LLM (specified or default) for synthesis.
  754. result = await client.tools.research_and_synthesize_report(
  755. topic="Latest advances in AI-powered drug discovery using graph neural networks",
  756. instructions={
  757. "search_query": "graph neural networks drug discovery 2024 research",
  758. "search_engines": ["google", "duckduckgo"], # Use multiple search engines
  759. "urls_to_include": ["nature.com", "sciencemag.org", "arxiv.org", "pubmed.ncbi.nlm.nih.gov"], # Prioritize these domains
  760. "max_urls_to_process": 7, # Limit the number of pages to visit/scrape
  761. "min_content_length": 500, # Ignore pages with very little content
  762. "focus_areas": ["novel molecular structures", "binding affinity prediction", "clinical trial results"], # Guide the synthesis
  763. "report_format": "markdown", # Desired output format
  764. "report_length": "detailed", # comprehensive, detailed, summary
  765. "llm_model": "anthropic/claude-3-5-sonnet-20241022" # Specify LLM for synthesis
  766. }
  767. )
  768. if result["success"]:
  769. print("\nResearch report generated successfully!")
  770. print(f"Processed {len(result.get('extracted_data', []))} sources.")
  771. print(f"Total processing time: {result.get('processing_time', 'N/A'):.2f}s")
  772. print(f"Estimated cost: ${result.get('total_cost', 0.0):.6f}") # Includes LLM synthesis cost
  773. print("\n--- Research Report ---")
  774. print(result['report'])
  775. print("-----------------------")
  776. else:
  777. print(f"\nBrowser research failed: {result.get('error', 'Unknown error')}")
  778. if 'details' in result: print(f"Details: {result['details']}")
  779. await client.close()
  780. # if __name__ == "__main__": asyncio.run(browser_research_example())
  781. ```
  782. ### Cognitive Memory System Usage
  783. ```python
  784. import asyncio
  785. from mcp.client import Client
  786. import uuid
  787. async def cognitive_memory_example():
  788. client = Client("http://localhost:8013")
  789. # Generate a unique ID for this session/workflow if not provided
  790. workflow_id = str(uuid.uuid4())
  791. print(f"Using Workflow ID: {workflow_id}")
  792. print("\nCreating a workflow context...")
  793. # Create a workflow context to group related memories and actions
  794. workflow_response = await client.tools.create_workflow(
  795. workflow_id=workflow_id,
  796. title="Quantum Computing Investment Analysis",
  797. description="Analyzing the impact of quantum computing on financial markets.",
  798. goal="Identify potential investment opportunities or risks."
  799. )
  800. if not workflow_response["success"]: print(f"Error creating workflow: {workflow_response['error']}")
  801. print("\nRecording an agent action...")
  802. # Record the start of a research action
  803. action_response = await client.tools.record_action_start(
  804. workflow_id=workflow_id,
  805. action_type="research",
  806. title="Initial literature review on quantum algorithms in finance",
  807. reasoning="Need to understand the current state-of-the-art before assessing impact."
  808. )
  809. action_id = action_response.get("action_id") if action_response["success"] else None
  810. if not action_id: print(f"Error starting action: {action_response['error']}")
  811. print("\nStoring facts in semantic memory...")
  812. # Store some key facts discovered during research
  813. memory1 = await client.tools.store_memory(
  814. workflow_id=workflow_id,
  815. content="Shor's algorithm can break RSA encryption, posing a threat to current financial security.",
  816. memory_type="fact", memory_level="semantic", importance=9.0,
  817. tags=["quantum_algorithm", "cryptography", "risk", "shor"]
  818. )
  819. memory2 = await client.tools.store_memory(
  820. workflow_id=workflow_id,
  821. content="Quantum annealing (e.g., D-Wave) shows promise for portfolio optimization problems.",
  822. memory_type="fact", memory_level="semantic", importance=7.5,
  823. tags=["quantum_computing", "finance", "optimization", "annealing"]
  824. )
  825. if memory1["success"]: print(f"Stored memory ID: {memory1['memory_id']}")
  826. if memory2["success"]: print(f"Stored memory ID: {memory2['memory_id']}")
  827. print("\nStoring an observation (episodic memory)...")
  828. # Store an observation from a specific event/document
  829. obs_memory = await client.tools.store_memory(
  830. workflow_id=workflow_id,
  831. content="Read Nature article (doi:...) suggesting experimental quantum advantage in a specific financial modeling task.",
  832. memory_type="observation", memory_level="episodic", importance=8.0,
  833. source="Nature Article XYZ", timestamp="2024-07-20T10:00:00Z", # Example timestamp
  834. tags=["research_finding", "publication", "finance_modeling"]
  835. )
  836. if obs_memory["success"]: print(f"Stored episodic memory ID: {obs_memory['memory_id']}")
  837. print("\nSearching for relevant memories...")
  838. # Search for memories related to financial risks
  839. search_results = await client.tools.hybrid_search_memories(
  840. workflow_id=workflow_id,
  841. query="What are the financial risks associated with quantum computing?",
  842. top_k=5, memory_type="fact", # Search for facts first
  843. semantic_weight=0.7, keyword_weight=0.3 # Example weighting for hybrid search
  844. )
  845. if search_results["success"]:
  846. print(f"Found {len(search_results['results'])} relevant memories:")
  847. for res in search_results["results"]:
  848. print(f" - Score: {res['score']:.4f}, ID: {res['memory_id']}, Content: {res['content'][:80]}...")
  849. else:
  850. print(f"Memory search failed: {search_results['error']}")
  851. print("\nGenerating a reflection based on stored memories...")
  852. # Generate insights or reflections based on the accumulated knowledge in the workflow
  853. reflection_response = await client.tools.generate_reflection(
  854. workflow_id=workflow_id,
  855. reflection_type="summary_and_next_steps", # e.g., insights, risks, opportunities
  856. context_query="Summarize the key findings about quantum finance impact and suggest next research actions."
  857. )
  858. if reflection_response["success"]:
  859. print("Generated Reflection:")
  860. print(reflection_response["reflection"])
  861. else:
  862. print(f"Reflection generation failed: {reflection_response['error']}")
  863. # Mark the action as completed (assuming research phase is done)
  864. if action_id:
  865. print("\nCompleting the research action...")
  866. await client.tools.record_action_end(
  867. workflow_id=workflow_id, action_id=action_id, status="completed",
  868. outcome="Gathered initial understanding of quantum algorithms in finance and associated risks."
  869. )
  870. await client.close()
  871. # if __name__ == "__main__": asyncio.run(cognitive_memory_example())
  872. ```
  873. ### Excel Spreadsheet Automation
  874. ```python
  875. import asyncio
  876. from mcp.client import Client
  877. import os
  878. async def excel_automation_example():
  879. client = Client("http://localhost:8013")
  880. output_dir = "excel_outputs"
  881. os.makedirs(output_dir, exist_ok=True)
  882. output_path = os.path.join(output_dir, "financial_model.xlsx")
  883. print(f"Requesting creation of Excel financial model at {output_path}...")
  884. # Example: Create a financial model using natural language instructions
  885. create_result = await client.tools.excel_execute(
  886. instruction="Create a simple 3-year financial projection.\n"
  887. "Sheet name: 'Projections'.\n"
  888. "Columns: Year 1, Year 2, Year 3.\n"
  889. "Rows: Revenue, COGS, Gross Profit, Operating Expenses, Net Income.\n"
  890. "Data: Start Revenue at $100,000, grows 20% annually.\n"
  891. "COGS is 40% of Revenue.\n"
  892. "Operating Expenses start at $30,000, grow 10% annually.\n"
  893. "Calculate Gross Profit (Revenue - COGS) and Net Income (Gross Profit - OpEx).\n"
  894. "Format currency as $#,##0. Apply bold headers and add a light blue fill to the header row.",
  895. file_path=output_path, # Server needs write access to this path/directory if relative
  896. operation_type="create", # create, modify, analyze, format
  897. # sheet_name="Projections", # Can specify sheet if modifying
  898. # cell_range="A1:D6", # Can specify range
  899. show_excel=False # Run Excel in the background (if applicable on the server)
  900. )
  901. if create_result["success"]:
  902. print(f"Excel creation successful: {create_result['message']}")
  903. print(f"File saved at: {create_result.get('output_file_path', output_path)}") # Confirm output path
  904. # Example: Modify the created file - add a chart
  905. print("\nRequesting modification: Add a Revenue chart...")
  906. modify_result = await client.tools.excel_execute(
  907. instruction="Add a column chart showing Revenue for Year 1, Year 2, Year 3. "
  908. "Place it below the table. Title the chart 'Revenue Projection'.",
  909. file_path=output_path, # Use the previously created file
  910. operation_type="modify",
  911. sheet_name="Projections" # Specify the sheet to modify
  912. )
  913. if modify_result["success"]:
  914. print(f"Excel modification successful: {modify_result['message']}")
  915. print(f"File updated at: {modify_result.get('output_file_path', output_path)}")
  916. else:
  917. print(f"Excel modification failed: {modify_result['error']}")
  918. else:
  919. print(f"Excel creation failed: {create_result['error']}")
  920. if 'details' in create_result: print(f"Details: {create_result['details']}")
  921. # Example: Analyze formulas (if the tool supports it)
  922. # analysis_result = await client.tools.excel_analyze_formulas(...)
  923. await client.close()
  924. # if __name__ == "__main__": asyncio.run(excel_automation_example())
  925. ```
  926. ### Multi-Provider Comparison
  927. ```python
  928. import asyncio
  929. from mcp.client import Client
  930. async def multi_provider_completion_example():
  931. client = Client("http://localhost:8013")
  932. prompt = "Explain the concept of 'Chain of Thought' prompting for Large Language Models."
  933. print(f"Requesting completions for prompt: '{prompt}' from multiple providers...")
  934. # Request the same prompt from different models/providers
  935. multi_response = await client.tools.multi_completion(
  936. prompt=prompt,
  937. providers=[
  938. {"provider": "openai", "model": "gpt-4.1-mini", "temperature": 0.5},
  939. {"provider": "anthropic", "model": "claude-3-5-sonnet-20241022", "temperature": 0.5},
  940. {"provider": "gemini", "model": "gemini-2.0-pro", "temperature": 0.5},
  941. # {"provider": "deepseek", "model": "deepseek-chat", "temperature": 0.5}, # Add others if configured
  942. ],
  943. # Common parameters applied to all if not specified per provider
  944. max_tokens=300
  945. )
  946. if multi_response["success"]:
  947. print("\n--- Multi-completion Results ---")
  948. total_cost = multi_response.get("total_cost", 0.0)
  949. print(f"Total Estimated Cost: ${total_cost:.6f}\n")
  950. for provider_key, result in multi_response["results"].items():
  951. print(f"--- Provider: {provider_key} ---")
  952. if result["success"]:
  953. print(f" Model: {result.get('model', 'N/A')}")
  954. print(f" Cost: ${result.get('cost', 0.0):.6f}")
  955. print(f" Tokens: Input={result.get('input_tokens', 'N/A')}, Output={result.get('output_tokens', 'N/A')}")
  956. print(f" Completion:\n{result['completion']}\n")
  957. else:
  958. print(f" Error: {result['error']}\n")
  959. print("------------------------------")
  960. # An agent could now analyze these responses for consistency, detail, accuracy etc.
  961. else:
  962. print(f"\nMulti-completion request failed: {multi_response['error']}")
  963. await client.close()
  964. # if __name__ == "__main__": asyncio.run(multi_provider_completion_example())
  965. ```
  966. ### Cost-Optimized Workflow Execution
  967. ```python
  968. import asyncio
  969. from mcp.client import Client
  970. async def optimized_workflow_example():
  971. client = Client("http://localhost:8013")
  972. # Example document to process through the workflow
  973. document_content = """
  974. Project Alpha Report - Q3 2024
  975. Lead: Dr. Evelyn Reed (e.reed@example.com)
  976. Status: On Track
  977. Budget: $50,000 remaining. Spent $25,000 this quarter.
  978. Key Findings: Successful prototype development (v0.8). User testing feedback positive.
  979. Next Steps: Finalize documentation, prepare for Q4 deployment. Target date: 2024-11-15.
  980. Risks: Potential delay due to supplier issues for component X. Mitigation plan in place.
  981. """
  982. print("Defining a multi-stage workflow...")
  983. # Define a workflow with stages, dependencies, and provider preferences
  984. # Use ${stage_id.output_key} to pass outputs between stages
  985. workflow_definition = [
  986. {
  987. "stage_id": "summarize_report",
  988. "tool_name": "summarize_document",
  989. "params": {
  990. "document": document_content,
  991. "format": "bullet_points",
  992. "max_length": 100,
  993. # Let the server choose a cost-effective model for summarization
  994. "provider_preference": "cost", # 'cost', 'quality', 'speed', or specific like 'openai/gpt-4.1-mini'
  995. }
  996. # No 'depends_on', runs first
  997. # Default output key is 'summary' for this tool, access via ${summarize_report.summary}
  998. },
  999. {
  1000. "stage_id": "extract_key_info",
  1001. "tool_name": "extract_json", # Use JSON extraction for structured data
  1002. "params": {
  1003. "document": document_content,
  1004. "json_schema": {
  1005. "type": "object",
  1006. "properties": {
  1007. "project_lead": {"type": "string"},
  1008. "lead_email": {"type": "string", "format": "email"},
  1009. "status": {"type": "string"},
  1010. "budget_remaining": {"type": "string"},
  1011. "next_milestone_date": {"type": "string", "format": "date"}
  1012. },
  1013. "required": ["project_lead", "status", "next_milestone_date"]
  1014. },
  1015. # Prefer a model known for good structured data extraction, balancing cost
  1016. "provider_preference": "quality", # Prioritize quality for extraction
  1017. "preferred_models": ["openai/gpt-4o", "anthropic/claude-3-5-sonnet-20241022"] # Suggest specific models
  1018. }
  1019. },
  1020. {
  1021. "stage_id": "generate_follow_up_questions",
  1022. "tool_name": "generate_qa", # Assuming a tool that generates questions
  1023. "depends_on": ["summarize_report"], # Needs the summary first
  1024. "params": {
  1025. # Use the summary from the first stage as input
  1026. "document": "${summarize_report.summary}",
  1027. "num_questions": 3,
  1028. "provider_preference": "speed" # Use a fast model for question generation
  1029. }
  1030. # Default output key 'qa_pairs', access via ${generate_follow_up_questions.qa_pairs}
  1031. }
  1032. ]
  1033. print("Executing the optimized workflow...")
  1034. # Execute the workflow - the server handles dependencies and model selection
  1035. results = await client.tools.execute_optimized_workflow(
  1036. workflow=workflow_definition
  1037. # Can also pass initial documents if workflow steps reference 'original_document'
  1038. # documents = {"report.txt": document_content}
  1039. )
  1040. if results["success"]:
  1041. print("\nWorkflow executed successfully!")
  1042. print(f" Total processing time: {results.get('processing_time', 'N/A'):.2f}s")
  1043. print(f" Total estimated cost: ${results.get('total_cost', 0.0):.6f}\n")
  1044. print("--- Stage Outputs ---")
  1045. for stage_id, output in results.get("stage_outputs", {}).items():
  1046. print(f"Stage: {stage_id}")
  1047. if output["success"]:
  1048. print(f" Provider/Model Used: {output.get('provider', 'N/A')}/{output.get('model', 'N/A')}")
  1049. print(f" Cost: ${output.get('cost', 0.0):.6f}")
  1050. print(f" Output: {output.get('result', 'N/A')}") # Access the primary result
  1051. # You might access specific keys like output.get('result', {}).get('summary') etc.
  1052. else:
  1053. print(f" Error: {output.get('error', 'Unknown error')}")
  1054. print("-" * 20)
  1055. else:
  1056. print(f"\nWorkflow execution failed: {results.get('error', 'Unknown error')}")
  1057. if 'details' in results: print(f"Details: {results['details']}")
  1058. await client.close()
  1059. # if __name__ == "__main__": asyncio.run(optimized_workflow_example())
  1060. ```
  1061. ### Entity Relation Graph Example
  1062. ```python
  1063. import asyncio
  1064. from mcp.client import Client
  1065. # import networkx as nx # To process the graph data if needed
  1066. # import matplotlib.pyplot as plt # To visualize
  1067. async def entity_graph_example():
  1068. client = Client("http://localhost:8013")
  1069. document_text = """
  1070. Meta Platforms, Inc., led by CEO Mark Zuckerberg, announced a partnership with IBM
  1071. on developing new AI hardware accelerators. The collaboration aims to challenge Nvidia's dominance.
  1072. IBM, headquartered in Armonk, New York, brings its deep expertise in semiconductor design.
  1073. The project, codenamed 'Synergy', is expected to yield results by late 2025.
  1074. """
  1075. print("Extracting entity relationships from text...")
  1076. # Request extraction of entities and their relationships
  1077. entity_graph_response = await client.tools.extract_entity_relations(
  1078. document=document_text,
  1079. entity_types=["organization", "person", "location", "date", "project"], # Specify desired entity types
  1080. relationship_types=["led_by", "partnership_with", "aims_to_challenge", "headquartered_in", "expected_by"], # Specify relationship types
  1081. # Optional parameters:
  1082. # provider_preference="quality", # Choose model strategy
  1083. # llm_model="anthropic/claude-3-5-sonnet-20241022", # Suggest a specific model
  1084. include_visualization=False # Set True to request image data if tool supports it
  1085. )
  1086. if entity_graph_response["success"]:
  1087. print("Entity relationship extraction successful.")
  1088. print(f"Estimated Cost: ${entity_graph_response.get('cost', 0.0):.6f}")
  1089. # The graph data might be in various formats (e.g., node-link list, adjacency list)
  1090. graph_data = entity_graph_response.get("graph_data")
  1091. print("\n--- Graph Data (Nodes & Edges) ---")
  1092. print(graph_data)
  1093. print("------------------------------------")
  1094. # Example: Query the extracted graph using another tool or LLM call
  1095. # (Assuming a separate query tool or using a general completion tool)
  1096. print("\nQuerying the extracted graph (example)...")
  1097. query_prompt = f"""
  1098. Based on the following graph data representing relationships extracted from a text:
  1099. {graph_data}
  1100. Answer the question: Who is the CEO of Meta Platforms, Inc.?
  1101. """
  1102. query_response = await client.tools.completion(
  1103. prompt=query_prompt, provider="openai", model="gpt-4.1-mini", max_tokens=50
  1104. )
  1105. if query_response["success"]:
  1106. print(f"Graph Query Answer: {query_response['completion']}")
  1107. else:
  1108. print(f"Graph query failed: {query_response['error']}")
  1109. else:
  1110. print(f"Entity relationship extraction failed: {entity_graph_response.get('error', 'Unknown error')}")
  1111. await client.close()
  1112. # if __name__ == "__main__": asyncio.run(entity_graph_example())
  1113. ```
  1114. ### Document Chunking
  1115. ```python
  1116. import asyncio
  1117. from mcp.client import Client
  1118. async def document_chunking_example():
  1119. client = Client("http://localhost:8013")
  1120. large_document = """
  1121. This is the first paragraph of a potentially very long document. It discusses various concepts.
  1122. The second paragraph continues the discussion, adding more details and nuances. Proper chunking
  1123. is crucial for processing large texts with Large Language Models, especially those with limited
  1124. context windows. Different strategies exist, such as fixed token size, sentence splitting,
  1125. or more advanced semantic chunking that tries to keep related ideas together. Overlap between
  1126. chunks helps maintain context across boundaries. This paragraph is intentionally made longer
  1127. to demonstrate how chunking might split it. It keeps going and going, describing the benefits
  1128. of effective text splitting for downstream tasks like summarization, question answering, and
  1129. retrieval-augmented generation (RAG). The goal is to create manageable pieces of text that
  1130. still retain coherence. Semantic chunking often uses embedding models to find natural breakpoints
  1131. in the text's meaning, potentially leading to better results than simple fixed-size chunks.
  1132. The final sentence of this example paragraph.
  1133. """ * 5 # Make it a bit longer for demonstration
  1134. print("Requesting document chunking...")
  1135. # Request chunking using a specific method and size
  1136. chunking_response = await client.tools.chunk_document(
  1137. document=large_document,
  1138. chunk_size=100, # Target size in tokens (approximate)
  1139. overlap=20, # Token overlap between consecutive chunks
  1140. method="semantic" # Options: "token", "sentence", "semantic", "structural" (if available)
  1141. )
  1142. if chunking_response["success"]:
  1143. print(f"Document successfully divided into {chunking_response['chunk_count']} chunks.")
  1144. print(f"Method Used: {chunking_response.get('method_used', 'N/A')}") # Confirm method if returned
  1145. print("\n--- Example Chunks ---")
  1146. for i, chunk in enumerate(chunking_response['chunks'][:3]): # Show first 3 chunks
  1147. print(f"Chunk {i+1} (Length: {len(chunk)} chars):")
  1148. print(f"'{chunk}'\n")
  1149. if chunking_response['chunk_count'] > 3: print("...")
  1150. print("----------------------")
  1151. # These chunks can now be passed individually to other tools (e.g., summarize_document)
  1152. else:
  1153. print(f"Document chunking failed: {chunking_response['error']}")
  1154. await client.close()
  1155. # if __name__ == "__main__": asyncio.run(document_chunking_example())
  1156. ```
  1157. ### Multi-Provider Completion (Duplicate of earlier example, kept for structure)
  1158. ```python
  1159. import asyncio
  1160. from mcp.client import Client
  1161. async def multi_provider_completion_example():
  1162. client = Client("http://localhost:8013")
  1163. prompt = "What are the main benefits of using the Model Context Protocol (MCP)?"
  1164. print(f"Requesting completions for prompt: '{prompt}' from multiple providers...")
  1165. multi_response = await client.tools.multi_completion(
  1166. prompt=prompt,
  1167. providers=[
  1168. {"provider": "openai", "model": "gpt-4.1-mini"},
  1169. {"provider": "anthropic", "model": "claude-3-5-haiku-20241022"},
  1170. {"provider": "gemini", "model": "gemini-2.0-flash-lite"}
  1171. # Add more configured providers as needed
  1172. ],
  1173. temperature=0.5,
  1174. max_tokens=250
  1175. )
  1176. if multi_response["success"]:
  1177. print("\n--- Multi-completion Results ---")
  1178. total_cost = multi_response.get("total_cost", 0.0)
  1179. print(f"Total Estimated Cost: ${total_cost:.6f}\n")
  1180. for provider_key, result in multi_response["results"].items():
  1181. print(f"--- Provider: {provider_key} ---")
  1182. if result["success"]:
  1183. print(f" Model: {result.get('model', 'N/A')}")
  1184. print(f" Cost: ${result.get('cost', 0.0):.6f}")
  1185. print(f" Completion:\n{result['completion']}\n")
  1186. else:
  1187. print(f" Error: {result['error']}\n")
  1188. print("------------------------------")
  1189. else:
  1190. print(f"\nMulti-completion request failed: {multi_response['error']}")
  1191. await client.close()
  1192. # if __name__ == "__main__": asyncio.run(multi_provider_completion_example())
  1193. ```
  1194. ### Structured Data Extraction (JSON)
  1195. ```python
  1196. import asyncio
  1197. from mcp.client import Client
  1198. import json
  1199. async def json_extraction_example():
  1200. client = Client("http://localhost:8013")
  1201. text_with_data = """
  1202. Meeting Minutes - Project Phoenix - 2024-07-21
  1203. Attendees: Alice (Lead), Bob (Dev), Charlie (QA)
  1204. Date: July 21, 2024
  1205. Project ID: PX-001
  1206. Discussion Points:
  1207. - Reviewed user feedback from v1.1 testing. Mostly positive.
  1208. - Identified performance bottleneck in data processing module. Bob to investigate. Assigned High priority.
  1209. - QA cycle for v1.2 planned to start next Monday (2024-07-29). Charlie confirmed readiness.
  1210. Action Items:
  1211. 1. Bob: Investigate performance issue. Due: 2024-07-26. Priority: High. Status: Open.
  1212. 2. Alice: Prepare v1.2 release notes. Due: 2024-07-28. Priority: Medium. Status: Open.
  1213. """
  1214. # Define the desired JSON structure (schema)
  1215. desired_schema = {
  1216. "type": "object",
  1217. "properties": {
  1218. "project_name": {"type": "string", "description": "Name of the project"},
  1219. "meeting_date": {"type": "string", "format": "date", "description": "Date of the meeting"},
  1220. "attendees": {"type": "array", "items": {"type": "string"}, "description": "List of attendee names"},
  1221. "action_items": {
  1222. "type": "array",
  1223. "items": {
  1224. "type": "object",
  1225. "properties": {
  1226. "task": {"type": "string"},
  1227. "assigned_to": {"type": "string"},
  1228. "due_date": {"type": "string", "format": "date"},
  1229. "priority": {"type": "string", "enum": ["Low", "Medium", "High"]},
  1230. "status": {"type": "string", "enum": ["Open", "In Progress", "Done"]}
  1231. },
  1232. "required": ["task", "assigned_to", "due_date", "priority", "status"]
  1233. }
  1234. }
  1235. },
  1236. "required": ["project_name", "meeting_date", "attendees", "action_items"]
  1237. }
  1238. print("Requesting JSON extraction based on schema...")
  1239. # Request extraction using a model capable of following JSON schema instructions
  1240. json_response = await client.tools.extract_json(
  1241. document=text_with_data,
  1242. json_schema=desired_schema,
  1243. provider="openai", # OpenAI models are generally good at this
  1244. model="gpt-4o", # Use a capable model like GPT-4o or Claude 3.5 Sonnet
  1245. # provider_preference="quality" # Could also use preference
  1246. )
  1247. if json_response["success"]:
  1248. print("JSON extraction successful.")
  1249. print(f"Estimated Cost: ${json_response.get('cost', 0.0):.6f}")
  1250. # The extracted data should conform to the schema
  1251. extracted_json_data = json_response.get('json_data')
  1252. print("\n--- Extracted JSON Data ---")
  1253. # Pretty print the JSON
  1254. print(json.dumps(extracted_json_data, indent=2))
  1255. print("---------------------------")
  1256. # Optionally, validate the output against the schema client-side (requires jsonschema library)
  1257. # try:
  1258. # from jsonschema import validate
  1259. # validate(instance=extracted_json_data, schema=desired_schema)
  1260. # print("\nClient-side validation successful: Output matches schema.")
  1261. # except ImportError:
  1262. # print("\n(Install jsonschema to perform client-side validation)")
  1263. # except Exception as e:
  1264. # print(f"\nClient-side validation failed: {e}")
  1265. else:
  1266. print(f"JSON Extraction Error: {json_response.get('error', 'Unknown error')}")
  1267. if 'details' in json_response: print(f"Details: {json_response['details']}")
  1268. await client.close()
  1269. # if __name__ == "__main__": asyncio.run(json_extraction_example())
  1270. ```
  1271. ### Retrieval-Augmented Generation (RAG) Query
  1272. ```python
  1273. import asyncio
  1274. from mcp.client import Client
  1275. async def rag_query_example():
  1276. # This example assumes the Ultimate MCP Server has been configured with a RAG pipeline,
  1277. # including a vector store/index containing relevant documents.
  1278. client = Client("http://localhost:8013")
  1279. query = "What are the latest treatment options for mitigating Alzheimer's disease according to recent studies?"
  1280. print(f"Performing RAG query: '{query}'...")
  1281. # Call the RAG tool, which handles retrieval and generation
  1282. rag_response = await client.tools.rag_query( # Assuming the tool name is 'rag_query'
  1283. query=query,
  1284. # Optional parameters to control the RAG process:
  1285. index_name="medical_research_papers", # Specify the index/collection to search
  1286. top_k=3, # Retrieve top 3 most relevant documents/chunks
  1287. # filter={"year": {"$gte": 2023}}, # Example filter (syntax depends on vector store)
  1288. # generation_model={"provider": "anthropic", "model": "claude-3-5-sonnet-20241022"}, # Specify generation model
  1289. # instruction_prompt="Based on the provided context, answer the user's query concisely." # Customize generation prompt
  1290. )
  1291. if rag_response["success"]:
  1292. print("\nRAG query successful.")
  1293. print(f"Estimated Cost: ${rag_response.get('cost', 0.0):.6f}") # Includes retrieval + generation cost
  1294. print("\n--- Generated Answer ---")
  1295. print(rag_response.get('answer', 'No answer generated.'))
  1296. print("------------------------")
  1297. # The response might also include details about the retrieved sources
  1298. retrieved_sources = rag_response.get('sources', [])
  1299. if retrieved_sources:
  1300. print("\n--- Retrieved Sources ---")
  1301. for i, source in enumerate(retrieved_sources):
  1302. print(f"Source {i+1}:")
  1303. print(f" ID: {source.get('id', 'N/A')}")
  1304. print(f" Score: {source.get('score', 'N/A'):.4f}")
  1305. # Depending on RAG setup, might include metadata or text snippet
  1306. print(f" Content Snippet: {source.get('text', '')[:150]}...")
  1307. print("-" * 15)
  1308. print("-----------------------")
  1309. else:
  1310. print("\nNo sources information provided in the response.")
  1311. else:
  1312. print(f"\nRAG Query Error: {rag_response.get('error', 'Unknown error')}")
  1313. if 'details' in rag_response: print(f"Details: {rag_response['details']}")
  1314. await client.close()
  1315. # if __name__ == "__main__": asyncio.run(rag_query_example())
  1316. ```
  1317. ### Fused Search (Keyword + Semantic)
  1318. ```python
  1319. import asyncio
  1320. from mcp.client import Client
  1321. async def fused_search_example():
  1322. # This example assumes the server is configured with a hybrid search provider like Marqo.
  1323. client = Client("http://localhost:8013")
  1324. query = "impact of AI on software development productivity and code quality"
  1325. print(f"Performing fused search for: '{query}'...")
  1326. # Call the fused search tool
  1327. fused_search_response = await client.tools.fused_search( # Assuming tool name is 'fused_search'
  1328. query=query,
  1329. # --- Parameters specific to the hybrid search backend (e.g., Marqo) ---
  1330. index_name="tech_articles_index", # Specify the target index
  1331. searchable_attributes=["title", "content"], # Fields to search within
  1332. limit=5, # Number of results to return
  1333. # Tunable weights for keyword vs. semantic relevance (example)
  1334. hybrid_factors={"keyword_weight": 0.4, "semantic_weight": 0.6},
  1335. # Optional filter string (syntax depends on backend)
  1336. filter_string="publication_year >= 2023 AND source_type='journal'"
  1337. # --------------------------------------------------------------------
  1338. )
  1339. if fused_search_response["success"]:
  1340. print("\nFused search successful.")
  1341. results = fused_search_response.get("results", [])
  1342. print(f"Found {len(results)} hits.")
  1343. if results:
  1344. print("\n--- Search Results ---")
  1345. for i, hit in enumerate(results):
  1346. print(f"Result {i+1}:")
  1347. # Fields depend on Marqo index structure and what's returned
  1348. print(f" ID: {hit.get('_id', 'N/A')}")
  1349. print(f" Score: {hit.get('_score', 'N/A'):.4f}") # Combined score
  1350. print(f" Title: {hit.get('title', 'N/A')}")
  1351. print(f" Content Snippet: {hit.get('content', '')[:150]}...")
  1352. # Print highlight info if available
  1353. highlights = hit.get('_highlights', {})
  1354. if highlights: print(f" Highlights: {highlights}")
  1355. print("-" * 15)
  1356. print("--------------------")
  1357. else:
  1358. print("No results found matching the criteria.")
  1359. else:
  1360. print(f"\nFused Search Error: {fused_search_response.get('error', 'Unknown error')}")
  1361. if 'details' in fused_search_response: print(f"Details: {fused_search_response['details']}")
  1362. await client.close()
  1363. # if __name__ == "__main__": asyncio.run(fused_search_example())
  1364. ```
  1365. ### Local Text Processing
  1366. ```python
  1367. import asyncio
  1368. from mcp.client import Client
  1369. async def local_text_processing_example():
  1370. client = Client("http://localhost:8013")
  1371. # Example assumes a tool named 'process_local_text' exists on the server
  1372. # that bundles various non-LLM text operations.
  1373. raw_text = " This text has EXTRA whitespace,\n\nmultiple newlines, \t tabs, and needs Case Normalization. "
  1374. print("Requesting local text processing operations...")
  1375. local_process_response = await client.tools.process_local_text(
  1376. text=raw_text,
  1377. operations=[
  1378. {"action": "trim_whitespace"}, # Remove leading/trailing whitespace
  1379. {"action": "normalize_whitespace"}, # Collapse multiple spaces/tabs to single space
  1380. {"action": "remove_blank_lines"}, # Remove empty lines
  1381. {"action": "lowercase"} # Convert to lowercase
  1382. # Other potential actions: uppercase, remove_punctuation, normalize_newlines, etc.
  1383. ]
  1384. )
  1385. if local_process_response["success"]:
  1386. print("\nLocal text processing successful.")
  1387. print(f"Original Text:\n'{raw_text}'")
  1388. print(f"\nProcessed Text:\n'{local_process_response['processed_text']}'")
  1389. # Note: This operation should ideally have zero LLM cost.
  1390. print(f"Cost: ${local_process_response.get('cost', 0.0):.6f}")
  1391. else:
  1392. print(f"\nLocal Text Processing Error: {local_process_response['error']}")
  1393. await client.close()
  1394. # if __name__ == "__main__": asyncio.run(local_text_processing_example())
  1395. ```
  1396. ### Browser Automation Example: Getting Started and Basic Interaction
  1397. ```python
  1398. import asyncio
  1399. from mcp.client import Client
  1400. async def browser_basic_interaction_example():
  1401. # This example shows fundamental browser actions controlled by an agent
  1402. client = Client("http://localhost:8013")
  1403. print("--- Browser Automation: Basic Interaction ---")
  1404. # 1. Initialize the browser (creates a browser instance on the server)
  1405. print("\nInitializing browser (headless)...")
  1406. # `headless=True` runs without a visible GUI window (common for automation)
  1407. init_response = await client.tools.browser_init(headless=True, browser_type="chromium")
  1408. if not init_response["success"]:
  1409. print(f"Browser initialization failed: {init_response.get('error', 'Unknown error')}")
  1410. await client.close()
  1411. return
  1412. print("Browser initialized successfully.")
  1413. # Might return session ID if needed for subsequent calls, depends on tool design
  1414. # 2. Navigate to a page
  1415. target_url = "https://example.com/"
  1416. print(f"\nNavigating to {target_url}...")
  1417. # `wait_until` controls when navigation is considered complete
  1418. nav_response = await client.tools.browser_navigate(
  1419. url=target_url,
  1420. wait_until="domcontentloaded" # Options: load, domcontentloaded, networkidle, commit
  1421. )
  1422. if nav_response["success"]:
  1423. print(f"Navigation successful.")
  1424. print(f" Current URL: {nav_response.get('url', 'N/A')}")
  1425. print(f" Page Title: {nav_response.get('title', 'N/A')}")
  1426. # The 'snapshot' gives the agent context about the page state (accessibility tree)
  1427. # print(f" Snapshot: {nav_response.get('snapshot', 'N/A')}")
  1428. else:
  1429. print(f"Navigation failed: {nav_response.get('error', 'Unknown error')}")
  1430. # Attempt to close browser even if navigation failed
  1431. await client.tools.browser_close()
  1432. await client.close()
  1433. return
  1434. # 3. Extract text content using a CSS selector
  1435. selector = "h1" # CSS selector for the main heading
  1436. print(f"\nExtracting text from selector '{selector}'...")
  1437. text_response = await client.tools.browser_get_text(selector=selector)
  1438. if text_response["success"]:
  1439. print(f"Extracted text: '{text_response.get('text', 'N/A')}'")
  1440. else:
  1441. print(f"Text extraction failed: {text_response.get('error', 'Unknown error')}")
  1442. # Optionally check text_response['snapshot'] for page state at time of failure
  1443. # 4. Take a screenshot (optional)
  1444. print("\nTaking a screenshot...")
  1445. screenshot_response = await client.tools.browser_screenshot(
  1446. file_path="example_com_screenshot.png", # Path where server saves the file
  1447. full_page=False, # Capture only the viewport
  1448. image_format="png" # png or jpeg
  1449. )
  1450. if screenshot_response["success"]:
  1451. print(f"Screenshot saved successfully on server at: {screenshot_response.get('saved_path', 'N/A')}")
  1452. # Agent might use this path with a filesystem tool to retrieve the image if needed
  1453. else:
  1454. print(f"Screenshot failed: {screenshot_response.get('error', 'Unknown error')}")
  1455. # 5. Close the browser session
  1456. print("\nClosing the browser...")
  1457. close_response = await client.tools.browser_close()
  1458. if close_response["success"]:
  1459. print("Browser closed successfully.")
  1460. else:
  1461. # Log error, but might happen if browser already crashed
  1462. print(f"Browser close failed (might be expected if previous steps failed): {close_response.get('error', 'Unknown error')}")
  1463. print("--- Browser Automation Example Complete ---")
  1464. await client.close()
  1465. # if __name__ == "__main__": asyncio.run(browser_basic_interaction_example())
  1466. ```
  1467. ### Running a Model Tournament
  1468. ```python
  1469. import asyncio
  1470. from mcp.client import Client
  1471. import json
  1472. async def model_tournament_example():
  1473. client = Client("http://localhost:8013")
  1474. # Define the task and prompt for the tournament
  1475. task_prompt = "Write a Python function that takes a list of integers and returns a new list containing only the even numbers."
  1476. # Optional: Provide ground truth for automated evaluation if the tool supports it
  1477. ground_truth_code = """
  1478. def get_even_numbers(numbers):
  1479. \"\"\"Returns a new list containing only the even numbers from the input list.\"\"\"
  1480. return [num for num in numbers if num % 2 == 0]
  1481. """
  1482. print("Setting up and running a model tournament for code generation...")
  1483. # Call the tournament tool
  1484. tournament_response = await client.tools.run_model_tournament(
  1485. task_type="code_generation", # Helps select appropriate evaluation metrics
  1486. prompt=task_prompt,
  1487. # List of models/providers to compete
  1488. competitors=[
  1489. {"provider": "openai", "model": "gpt-4.1-mini", "temperature": 0.2},
  1490. {"provider": "anthropic", "model": "claude-3-5-sonnet-20241022", "temperature": 0.2},
  1491. {"provider": "deepseek", "model": "deepseek-coder", "temperature": 0.2}, # Specialized coder model
  1492. {"provider": "gemini", "model": "gemini-2.0-pro", "temperature": 0.2},
  1493. ],
  1494. # Criteria for evaluating the generated code
  1495. evaluation_criteria=["correctness", "efficiency", "readability", "docstring_quality"],
  1496. # Provide ground truth if available for automated correctness checks
  1497. ground_truth=ground_truth_code,
  1498. # Optional: Specify an LLM to act as the judge for qualitative criteria
  1499. evaluation_model={"provider": "anthropic", "model": "claude-3-5-opus-20240229"}, # Use a powerful model for judging
  1500. num_rounds=1 # Run multiple rounds for stability if needed
  1501. )
  1502. if tournament_response["success"]:
  1503. print("\n--- Model Tournament Results ---")
  1504. print(f"Task Prompt: {task_prompt}")
  1505. print(f"Total Estimated Cost: ${tournament_response.get('total_cost', 0.0):.6f}\n")
  1506. # Display the ranking
  1507. ranking = tournament_response.get("ranking", [])
  1508. if ranking:
  1509. print("Overall Ranking:")
  1510. for i, result in enumerate(ranking):
  1511. provider = result.get('provider', 'N/A')
  1512. model = result.get('model', 'N/A')
  1513. score = result.get('overall_score', 'N/A')
  1514. cost = result.get('cost', 0.0)
  1515. print(f" {i+1}. {provider}/{model} - Score: {score:.2f}/10 - Cost: ${cost:.6f}")
  1516. else:
  1517. print("No ranking information available.")
  1518. # Display detailed results for each competitor
  1519. detailed_results = tournament_response.get("results", {})
  1520. if detailed_results:
  1521. print("\nDetailed Scores per Competitor:")
  1522. for competitor_key, details in detailed_results.items():
  1523. print(f" Competitor: {competitor_key}")
  1524. print(f" Generated Code:\n```python\n{details.get('output', 'N/A')}\n```")
  1525. scores = details.get('scores', {})
  1526. if scores:
  1527. for criterion, score_value in scores.items():
  1528. print(f" - {criterion}: {score_value}")
  1529. print("-" * 10)
  1530. print("------------------------------")
  1531. else:
  1532. print(f"\nModel Tournament Failed: {tournament_response.get('error', 'Unknown error')}")
  1533. if 'details' in tournament_response: print(f"Details: {tournament_response['details']}")
  1534. await client.close()
  1535. # if __name__ == "__main__": asyncio.run(model_tournament_example())
  1536. ```
  1537. ### Meta Tools for Tool Discovery
  1538. ```python
  1539. import asyncio
  1540. from mcp.client import Client
  1541. import json
  1542. async def meta_tools_example():
  1543. client = Client("http://localhost:8013")
  1544. print("--- Meta Tools Example ---")
  1545. # 1. List all available tools
  1546. print("\nFetching list of available tools...")
  1547. # Assumes a tool named 'list_tools' provides this info
  1548. list_tools_response = await client.tools.list_tools(include_schemas=False) # Set True for full schemas
  1549. if list_tools_response["success"]:
  1550. tools = list_tools_response.get("tools", {})
  1551. print(f"Found {len(tools)} available tools:")
  1552. for tool_name, tool_info in tools.items():
  1553. description = tool_info.get('description', 'No description available.')
  1554. print(f" - {tool_name}: {description[:100]}...") # Print truncated description
  1555. else:
  1556. print(f"Failed to list tools: {list_tools_response.get('error', 'Unknown error')}")
  1557. # 2. Get detailed information about a specific tool
  1558. tool_to_inspect = "extract_json"
  1559. print(f"\nFetching details for tool: '{tool_to_inspect}'...")
  1560. # Assumes a tool like 'get_tool_info' or using list_tools with specific name/schema flag
  1561. tool_info_response = await client.tools.list_tools(tool_names=[tool_to_inspect], include_schemas=True)
  1562. if tool_info_response["success"] and tool_to_inspect in tool_info_response.get("tools", {}):
  1563. tool_details = tool_info_response["tools"][tool_to_inspect]
  1564. print(f"\nDetails for '{tool_to_inspect}':")
  1565. print(f" Description: {tool_details.get('description', 'N/A')}")
  1566. # Print the parameter schema if available
  1567. schema = tool_details.get('parameters', {}).get('json_schema', {})
  1568. if schema:
  1569. print(f" Parameter Schema:\n{json.dumps(schema, indent=2)}")
  1570. else:
  1571. print(" Parameter Schema: Not available.")
  1572. else:
  1573. print(f"Failed to get info for tool '{tool_to_inspect}': {tool_info_response.get('error', 'Not found or error')}")
  1574. # 3. Get tool recommendations for a task (if such a meta tool exists)
  1575. task_description = "Read data from a PDF file, extract tables, and save them as CSV."
  1576. print(f"\nGetting tool recommendations for task: '{task_description}'...")
  1577. # Assumes a tool like 'get_tool_recommendations'
  1578. recommendations_response = await client.tools.get_tool_recommendations(
  1579. task=task_description,
  1580. constraints={"priority": "accuracy", "max_cost_per_doc": 0.10} # Example constraints
  1581. )
  1582. if recommendations_response["success"]:
  1583. print("Recommended Tool Workflow:")
  1584. recommendations = recommendations_response.get("recommendations", [])
  1585. if recommendations:
  1586. for i, step in enumerate(recommendations):
  1587. print(f" Step {i+1}: Tool='{step.get('tool', 'N/A')}' - Reason: {step.get('reason', 'N/A')}")
  1588. else:
  1589. print(" No recommendations provided.")
  1590. else:
  1591. print(f"Failed to get recommendations: {recommendations_response.get('error', 'Unknown error')}")
  1592. print("\n--- Meta Tools Example Complete ---")
  1593. await client.close()
  1594. # if __name__ == "__main__": asyncio.run(meta_tools_example())
  1595. ```
  1596. ### Local Command-Line Text Processing (e.g., jq)
  1597. ```python
  1598. import asyncio
  1599. from mcp.client import Client
  1600. import json
  1601. async def local_cli_tool_example():
  1602. client = Client("http://localhost:8013")
  1603. print("--- Local CLI Tool Example (jq) ---")
  1604. # Example JSON data to be processed by jq
  1605. json_input_data = json.dumps({
  1606. "users": [
  1607. {"id": 1, "name": "Alice", "email": "alice@example.com", "status": "active"},
  1608. {"id": 2, "name": "Bob", "email": "bob@example.com", "status": "inactive"},
  1609. {"id": 3, "name": "Charlie", "email": "charlie@example.com", "status": "active"}
  1610. ],
  1611. "metadata": {"timestamp": "2024-07-21T12:00:00Z"}
  1612. })
  1613. # Define the jq filter to apply
  1614. # This filter selects active users and outputs their name and email
  1615. jq_filter = '.users[] | select(.status=="active") | {name: .name, email: .email}'
  1616. print(f"\nRunning jq with filter: '{jq_filter}' on input JSON...")
  1617. # Call the server tool that wraps jq (e.g., 'run_jq')
  1618. jq_result = await client.tools.run_jq(
  1619. args_str=jq_filter, # Pass the filter as arguments (check tool spec how it expects filters)
  1620. input_data=json_input_data, # Provide the JSON string as input
  1621. # Additional options might be available depending on the tool wrapper:
  1622. # e.g., output_format="json_lines" or "compact_json"
  1623. )
  1624. if jq_result["success"]:
  1625. print("jq execution successful.")
  1626. # stdout typically contains the result of the jq filter
  1627. print("\n--- jq Output (stdout) ---")
  1628. print(jq_result.get("stdout", "No output"))
  1629. print("--------------------------")
  1630. # stderr might contain warnings or errors from jq itself
  1631. stderr_output = jq_result.get("stderr")
  1632. if stderr_output:
  1633. print("\n--- jq Stderr ---")

Lines 2,001–2,854 are not shown. The link to the file on GitHub has every line.

Ratings and comments

Sign in to rate this skill.

Sign in

Free to use. If it’s helped, pass it on.