{"id":26571000,"url":"https://github.com/lastmile-ai/mcp-agent","last_synced_at":"2025-05-11T13:58:38.637Z","repository":{"id":272678843,"uuid":"905016458","full_name":"lastmile-ai/mcp-agent","owner":"lastmile-ai","description":"Build effective agents using Model Context Protocol and simple workflow patterns","archived":false,"fork":false,"pushed_at":"2025-05-09T17:26:45.000Z","size":18439,"stargazers_count":4391,"open_issues_count":48,"forks_count":384,"subscribers_count":30,"default_branch":"main","last_synced_at":"2025-05-11T13:58:32.218Z","etag":null,"topics":["agents","ai","ai-agents","llm","llms","mcp","model-context-protocol","python"],"latest_commit_sha":null,"homepage":"","language":"Python","has_issues":true,"has_wiki":null,"has_pages":null,"mirror_url":null,"source_name":null,"license":"apache-2.0","status":null,"scm":"git","pull_requests_enabled":true,"icon_url":"https://github.com/lastmile-ai.png","metadata":{"files":{"readme":"README.md","changelog":null,"contributing":"CONTRIBUTING.md","funding":null,"license":"LICENSE","code_of_conduct":null,"threat_model":null,"audit":null,"citation":null,"codeowners":null,"security":null,"support":null,"governance":null,"roadmap":null,"authors":null,"dei":null,"publiccode":null,"codemeta":null,"zenodo":null}},"created_at":"2024-12-18T01:55:10.000Z","updated_at":"2025-05-11T09:17:47.000Z","dependencies_parsed_at":null,"dependency_job_id":"d4104ea9-2b52-43dc-87b0-dc1dec34eef7","html_url":"https://github.com/lastmile-ai/mcp-agent","commit_stats":null,"previous_names":["lastmile-ai/mcp-agent","saqadri/mcp-agent"],"tags_count":14,"template":false,"template_full_name":null,"repository_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lastmile-ai%2Fmcp-agent","tags_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lastmile-ai%2Fmcp-agent/tags","releases_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lastmile-ai%2Fmcp-agent/releases","manifests_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories/lastmile-ai%2Fmcp-agent/manifests","owner_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners/lastmile-ai","download_url":"https://codeload.github.com/lastmile-ai/mcp-agent/tar.gz/refs/heads/main","host":{"name":"GitHub","url":"https://github.com","kind":"github","repositories_count":253576262,"owners_count":21930169,"icon_url":"https://github.com/github.png","version":null,"created_at":"2022-05-30T11:31:42.601Z","updated_at":"2022-07-04T15:15:14.044Z","host_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub","repositories_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repositories","repository_names_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/repository_names","owners_url":"https://repos.ecosyste.ms/api/v1/hosts/GitHub/owners"}},"keywords":["agents","ai","ai-agents","llm","llms","mcp","model-context-protocol","python"],"created_at":"2025-03-22T22:19:28.117Z","updated_at":"2025-05-11T13:58:38.619Z","avatar_url":"https://github.com/lastmile-ai.png","language":"Python","funding_links":[],"categories":["Agentic AI ![](https://img.shields.io/badge/_-AGENTIC-22d3ee?style=flat-square\u0026logo=openai\u0026logoColor=white)","Frameworks \u0026 SDKs","MCP Middleware \u0026 Orchestration","Foundation Models, LLMs, and Agents","Python","Frameworks","📚 Projects (1974 total)","Design Primitives","🤖 AI/ML","MCP 更多玩法","A01_文本生成_文本对话","HarmonyOS","Agent Development Frameworks","4. Agentic AI \u0026 Multi-Agent Systems","Repos","🧪 Demos \u0026 Projects","Orchestration Frameworks","Table of Contents","MCP Ecosystem","MCP Frameworks and libraries","AI Agent Frameworks \u0026 SDKs","Tools","Tool / protocol / connector layer","MCP Servers \u0026 Protocol","🔎 Select Context","Catalog","🤖 AI \u0026 Machine Learning"],"sub_categories":["Agentic frameworks","Trading \u0026 Exchanges","Agent Protocols, Memory, and Tooling","Common Lisp","MCP Servers","Skills \u0026 MCP","🛠️ \u003ca name=\"other-tools-and-integrations\"\u003e\u003c/a\u003eOther Tools and Integrations","更多 MCP Server 资源","大语言对话模型及数据","Windows Manager","Frameworks","MCP Agents","AI Services","Core \u0026 Frameworks","Python","Orchestration Frameworks","Community","Codex Resources","Tools","MCP Frameworks","Harness Architecture \u0026 Orchestration"],"readme":"\u003cp align=\"center\"\u003e\n  \u003cimg src=\"https://github.com/user-attachments/assets/6f4e40c4-dc88-47b6-b965-5856b69416d2\" alt=\"Logo\" width=\"300\" /\u003e\n\u003c/p\u003e\n\n\u003cp align=\"center\"\u003e\n  \u003cem\u003eBuild effective agents with Model Context Protocol using simple, composable patterns.\u003c/em\u003e\n\n\u003cp align=\"center\"\u003e\n  \u003ca href=\"https://github.com/lastmile-ai/mcp-agent/tree/main/examples\" target=\"_blank\"\u003e\u003cstrong\u003eExamples\u003c/strong\u003e\u003c/a\u003e\n  |\n  \u003ca href=\"https://www.anthropic.com/research/building-effective-agents\" target=\"_blank\"\u003e\u003cstrong\u003eBuilding Effective Agents\u003c/strong\u003e\u003c/a\u003e\n  |\n  \u003ca href=\"https://modelcontextprotocol.io/introduction\" target=\"_blank\"\u003e\u003cstrong\u003eMCP\u003c/strong\u003e\u003c/a\u003e\n\u003c/p\u003e\n\n\u003cp align=\"center\"\u003e\n\u003ca href=\"https://pypi.org/project/mcp-agent/\"\u003e\u003cimg src=\"https://img.shields.io/pypi/v/mcp-agent?color=%2334D058\u0026label=pypi\" /\u003e\u003c/a\u003e\n\u003ca href=\"https://github.com/lastmile-ai/mcp-agent/issues\"\u003e\u003cimg src=\"https://img.shields.io/github/issues-raw/lastmile-ai/mcp-agent\" /\u003e\u003c/a\u003e\n\u003ca href=\"https://lmai.link/discord/mcp-agent\"\u003e\u003cimg src=\"https://shields.io/discord/1089284610329952357\" alt=\"discord\" /\u003e\u003c/a\u003e\n\u003cimg alt=\"Pepy Total Downloads\" src=\"https://img.shields.io/pepy/dt/mcp-agent?label=pypi%20%7C%20downloads\"/\u003e\n\u003ca href=\"https://github.com/lastmile-ai/mcp-agent/blob/main/LICENSE\"\u003e\u003cimg src=\"https://img.shields.io/pypi/l/mcp-agent\" /\u003e\u003c/a\u003e\n\u003c/p\u003e\n\n## Overview\n\n**`mcp-agent`** is a simple, composable framework to build agents using [Model Context Protocol](https://modelcontextprotocol.io/introduction).\n\n**Inspiration**: Anthropic announced 2 foundational updates for AI application developers:\n\n1. [Model Context Protocol](https://www.anthropic.com/news/model-context-protocol) - a standardized interface to let any software be accessible to AI assistants via MCP servers.\n2. [Building Effective Agents](https://www.anthropic.com/research/building-effective-agents) - a seminal writeup on simple, composable patterns for building production-ready AI agents.\n\n`mcp-agent` puts these two foundational pieces into an AI application framework:\n\n1. It handles the pesky business of managing the lifecycle of MCP server connections so you don't have to.\n2. It implements every pattern described in Building Effective Agents, and does so in a _composable_ way, allowing you to chain these patterns together.\n3. **Bonus**: It implements [OpenAI's Swarm](https://github.com/openai/swarm) pattern for multi-agent orchestration, but in a model-agnostic way.\n\nAltogether, this is the simplest and easiest way to build robust agent applications. Much like MCP, this project is in early development.\nWe welcome all kinds of [contributions](/CONTRIBUTING.md), feedback and your help in growing this to become a new standard.\n\n## Get Started\n\nWe recommend using [uv](https://docs.astral.sh/uv/) to manage your Python projects:\n\n```bash\nuv add \"mcp-agent\"\n```\n\nAlternatively:\n\n```bash\npip install mcp-agent\n```\n\n### Quickstart\n\n\u003e [!TIP]\n\u003e The [`examples`](/examples) directory has several example applications to get started with.\n\u003e To run an example, clone this repo, then:\n\u003e\n\u003e ```bash\n\u003e cd examples/basic/mcp_basic_agent # Or any other example\n\u003e cp mcp_agent.secrets.yaml.example mcp_agent.secrets.yaml # Update API keys\n\u003e uv run main.py\n\u003e ```\n\nHere is a basic \"finder\" agent that uses the fetch and filesystem servers to look up a file, read a blog and write a tweet. [Example link](./examples/basic/mcp_basic_agent/):\n\n\u003cdetails open\u003e\n\u003csummary\u003efinder_agent.py\u003c/summary\u003e\n\n```python\nimport asyncio\nimport os\n\nfrom mcp_agent.app import MCPApp\nfrom mcp_agent.agents.agent import Agent\nfrom mcp_agent.workflows.llm.augmented_llm_openai import OpenAIAugmentedLLM\n\napp = MCPApp(name=\"hello_world_agent\")\n\nasync def example_usage():\n    async with app.run() as mcp_agent_app:\n        logger = mcp_agent_app.logger\n        # This agent can read the filesystem or fetch URLs\n        finder_agent = Agent(\n            name=\"finder\",\n            instruction=\"\"\"You can read local files or fetch URLs.\n                Return the requested information when asked.\"\"\",\n            server_names=[\"fetch\", \"filesystem\"], # MCP servers this Agent can use\n        )\n\n        async with finder_agent:\n            # Automatically initializes the MCP servers and adds their tools for LLM use\n            tools = await finder_agent.list_tools()\n            logger.info(f\"Tools available:\", data=tools)\n\n            # Attach an OpenAI LLM to the agent (defaults to GPT-4o)\n            llm = await finder_agent.attach_llm(OpenAIAugmentedLLM)\n\n            # This will perform a file lookup and read using the filesystem server\n            result = await llm.generate_str(\n                message=\"Show me what's in README.md verbatim\"\n            )\n            logger.info(f\"README.md contents: {result}\")\n\n            # Uses the fetch server to fetch the content from URL\n            result = await llm.generate_str(\n                message=\"Print the first two paragraphs from https://www.anthropic.com/research/building-effective-agents\"\n            )\n            logger.info(f\"Blog intro: {result}\")\n\n            # Multi-turn interactions by default\n            result = await llm.generate_str(\"Summarize that in a 128-char tweet\")\n            logger.info(f\"Tweet: {result}\")\n\nif __name__ == \"__main__\":\n    asyncio.run(example_usage())\n\n```\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003emcp_agent.config.yaml\u003c/summary\u003e\n\n```yaml\nexecution_engine: asyncio\nlogger:\n  transports: [console] # You can use [file, console] for both\n  level: debug\n  path: \"logs/mcp-agent.jsonl\" # Used for file transport\n  # For dynamic log filenames:\n  # path_settings:\n  #   path_pattern: \"logs/mcp-agent-{unique_id}.jsonl\"\n  #   unique_id: \"timestamp\"  # Or \"session_id\"\n  #   timestamp_format: \"%Y%m%d_%H%M%S\"\n\nmcp:\n  servers:\n    fetch:\n      command: \"uvx\"\n      args: [\"mcp-server-fetch\"]\n    filesystem:\n      command: \"npx\"\n      args:\n        [\n          \"-y\",\n          \"@modelcontextprotocol/server-filesystem\",\n          \"\u003cadd_your_directories\u003e\",\n        ]\n\nopenai:\n  # Secrets (API keys, etc.) are stored in an mcp_agent.secrets.yaml file which can be gitignored\n  default_model: gpt-4o\n```\n\n\u003c/details\u003e\n\n\u003cdetails\u003e\n\u003csummary\u003eAgent output\u003c/summary\u003e\n\u003cimg width=\"2398\" alt=\"Image\" src=\"https://github.com/user-attachments/assets/eaa60fdf-bcc6-460b-926e-6fa8534e9089\" /\u003e\n\u003c/details\u003e\n\n## Table of Contents\n\n- [Why use mcp-agent?](#why-use-mcp-agent)\n- [Example Applications](#examples)\n  - [Claude Desktop](#claude-desktop)\n  - [Streamlit](#streamlit)\n    - [Gmail Agent](#gmail-agent)\n    - [RAG](#simple-rag-chatbot)\n  - [Marimo](#marimo)\n  - [Python](#python)\n    - [Swarm (CLI)](#swarm)\n- [Core Concepts](#core-components)\n- [Workflows Patterns](#workflows)\n  - [Augmented LLM](#augmentedllm)\n  - [Parallel](#parallel)\n  - [Router](#router)\n  - [Intent-Classifier](#intentclassifier)\n  - [Orchestrator-Workers](#orchestrator-workers)\n  - [Evaluator-Optimizer](#evaluator-optimizer)\n  - [OpenAI Swarm](#swarm-1)\n- [Advanced](#advanced)\n  - [Composing multiple workflows](#composability)\n  - [Signaling and Human input](#signaling-and-human-input)\n  - [App Config](#app-config)\n  - [MCP Server Management](#mcp-server-management)\n- [Contributing](#contributing)\n- [Roadmap](#roadmap)\n- [FAQs](#faqs)\n\n## Why use `mcp-agent`?\n\nThere are too many AI frameworks out there already. But `mcp-agent` is the only one that is purpose-built for a shared protocol - [MCP](https://modelcontextprotocol.io/introduction). It is also the most lightweight, and is closer to an agent pattern library than a framework.\n\nAs [more services become MCP-aware](https://github.com/punkpeye/awesome-mcp-servers), you can use mcp-agent to build robust and controllable AI agents that can leverage those services out-of-the-box.\n\n## Examples\n\nBefore we go into the core concepts of mcp-agent, let's show what you can build with it.\n\nIn short, you can build any kind of AI application with mcp-agent: multi-agent collaborative workflows, human-in-the-loop workflows, RAG pipelines and more.\n\n### Claude Desktop\n\nYou can integrate mcp-agent apps into MCP clients like Claude Desktop.\n\n#### mcp-agent server\n\nThis app wraps an mcp-agent application inside an MCP server, and exposes that server to Claude Desktop.\nThe app exposes agents and workflows that Claude Desktop can invoke to service of the user's request.\n\nhttps://github.com/user-attachments/assets/7807cffd-dba7-4f0c-9c70-9482fd7e0699\n\nThis demo shows a multi-agent evaluation task where each agent evaluates aspects of an input poem, and\nthen an aggregator summarizes their findings into a final response.\n\n**Details**: Starting from a user's request over text, the application:\n\n- dynamically defines agents to do the job\n- uses the appropriate workflow to orchestrate those agents (in this case the Parallel workflow)\n\n**Link to code**: [examples/basic/mcp_agent_server](./examples/basic/mcp_agent_server)\n\n\u003e [!NOTE]\n\u003e Huge thanks to [Jerron Lim (@StreetLamb)](https://github.com/StreetLamb)\n\u003e for developing and contributing this example!\n\n### Streamlit\n\nYou can deploy mcp-agent apps using Streamlit.\n\n#### Gmail agent\n\nThis app is able to perform read and write actions on gmail using text prompts -- i.e. read, delete, send emails, mark as read/unread, etc.\nIt uses an MCP server for Gmail.\n\nhttps://github.com/user-attachments/assets/54899cac-de24-4102-bd7e-4b2022c956e3\n\n**Link to code**: [gmail-mcp-server](https://github.com/jasonsum/gmail-mcp-server/blob/add-mcp-agent-streamlit/streamlit_app.py)\n\n\u003e [!NOTE]\n\u003e Huge thanks to [Jason Summer (@jasonsum)](https://github.com/jasonsum)\n\u003e for developing and contributing this example!\n\n#### Simple RAG Chatbot\n\nThis app uses a Qdrant vector database (via an MCP server) to do Q\u0026A over a corpus of text.\n\nhttps://github.com/user-attachments/assets/f4dcd227-cae9-4a59-aa9e-0eceeb4acaf4\n\n**Link to code**: [examples/usecases/streamlit_mcp_rag_agent](./examples/usecases/streamlit_mcp_rag_agent/)\n\n\u003e [!NOTE]\n\u003e Huge thanks to [Jerron Lim (@StreetLamb)](https://github.com/StreetLamb)\n\u003e for developing and contributing this example!\n\n### Marimo\n\n[Marimo](https://github.com/marimo-team/marimo) is a reactive Python notebook that replaces Jupyter and Streamlit.\nHere's the \"file finder\" agent from [Quickstart](#quickstart) implemented in Marimo:\n\n\u003cimg src=\"https://github.com/user-attachments/assets/139a95a5-e3ac-4ea7-9c8f-bad6577e8597\" width=\"400\"/\u003e\n\n**Link to code**: [examples/usecases/marimo_mcp_basic_agent](./examples/usecases/marimo_mcp_basic_agent/)\n\n\u003e [!NOTE]\n\u003e Huge thanks to [Akshay Agrawal (@akshayka)](https://github.com/akshayka)\n\u003e for developing and contributing this example!\n\n### Python\n\nYou can write mcp-agent apps as Python scripts or Jupyter notebooks.\n\n#### Swarm\n\nThis example demonstrates a multi-agent setup for handling different customer service requests in an airline context using the Swarm workflow pattern. The agents can triage requests, handle flight modifications, cancellations, and lost baggage cases.\n\nhttps://github.com/user-attachments/assets/b314d75d-7945-4de6-965b-7f21eb14a8bd\n\n**Link to code**: [examples/workflows/workflow_swarm](./examples/workflows/workflow_swarm/)\n\n## Core Components\n\nThe following are the building blocks of the mcp-agent framework:\n\n- **[MCPApp](./src/mcp_agent/app.py)**: global state and app configuration\n- **MCP server management**: [`gen_client`](./src/mcp_agent/mcp/gen_client.py) and [`MCPConnectionManager`](./src/mcp_agent/mcp/mcp_connection_manager.py) to easily connect to MCP servers.\n- **[Agent](./src/mcp_agent/agents/agent.py)**: An Agent is an entity that has access to a set of MCP servers and exposes them to an LLM as tool calls. It has a name and purpose (instruction).\n- **[AugmentedLLM](./src/mcp_agent/workflows/llm/augmented_llm.py)**: An LLM that is enhanced with tools provided from a collection of MCP servers. Every Workflow pattern described below is an `AugmentedLLM` itself, allowing you to compose and chain them together.\n\nEverything in the framework is a derivative of these core capabilities.\n\n## Workflows\n\nmcp-agent provides implementations for every pattern in Anthropic’s [Building Effective Agents](https://www.anthropic.com/research/building-effective-agents), as well as the OpenAI [Swarm](https://github.com/openai/swarm) pattern.\nEach pattern is model-agnostic, and exposed as an `AugmentedLLM`, making everything very composable.\n\n### AugmentedLLM\n\n[AugmentedLLM](./src/mcp_agent/workflows/llm/augmented_llm.py) is an LLM that has access to MCP servers and functions via Agents.\n\nLLM providers implement the AugmentedLLM interface to expose 3 functions:\n\n- `generate`: Generate message(s) given a prompt, possibly over multiple iterations and making tool calls as needed.\n- `generate_str`: Calls `generate` and returns result as a string output.\n- `generate_structured`: Uses [Instructor](https://github.com/instructor-ai/instructor) to return the generated result as a Pydantic model.\n\nAdditionally, `AugmentedLLM` has memory, to keep track of long or short-term history.\n\n\u003cdetails\u003e\n\u003csummary\u003eExample\u003c/summary\u003e\n\n```python\nfrom mcp_agent.agents.agent import Agent\nfrom mcp_agent.workflows.llm.augmented_llm_anthropic import AnthropicAugmentedLLM\n\nfinder_agent = Agent(\n    name=\"finder\",\n    instruction=\"You are an agent with filesystem + fetch access. Return the requested file or URL contents.\",\n    server_names=[\"fetch\", \"filesystem\"],\n)\n\nasync with finder_agent:\n   llm = await finder_agent.attach_llm(AnthropicAugmentedLLM)\n\n   result = await llm.generate_str(\n      message=\"Print the first 2 paragraphs of https://www.anthropic.com/research/building-effective-agents\",\n      # Can override model, tokens and other defaults\n   )\n   logger.info(f\"Result: {result}\")\n\n   # Multi-turn conversation\n   result = await llm.generate_str(\n      message=\"Summarize those paragraphs in a 128 character tweet\",\n   )\n   logger.info(f\"Result: {result}\")\n```\n\n\u003c/details\u003e\n\n### [Parallel](src/mcp_agent/workflows/parallel/parallel_llm.py)\n\n![Parallel workflow (Image credit: Anthropic)](https://www.anthropic.com/_next/image?url=https%3A%2F%2Fwww-cdn.anthropic.com%2Fimages%2F4zrzovbb%2Fwebsite%2F406bb032ca007fd1624f261af717d70e6ca86286-2401x1000.png\u0026w=3840\u0026q=75)\n\nFan-out tasks to multiple sub-agents and fan-in the results. Each subtask is an AugmentedLLM, as is the overall Parallel workflow, meaning each subtask can optionally be a more complex workflow itself.\n\n\u003e [!NOTE]\n\u003e\n\u003e **[Link to full example](examples/workflows/workflow_parallel/main.py)**\n\n\u003cdetails\u003e\n\u003csummary\u003eExample\u003c/summary\u003e\n\n```python\nproofreader = Agent(name=\"proofreader\", instruction=\"Review grammar...\")\nfact_checker = Agent(name=\"fact_checker\", instruction=\"Check factual consistency...\")\nstyle_enforcer = Agent(name=\"style_enforcer\", instruction=\"Enforce style guidelines...\")\n\ngrader = Agent(name=\"grader\", instruction=\"Combine feedback into a structured report.\")\n\nparallel = ParallelLLM(\n    fan_in_agent=grader,\n    fan_out_agents=[proofreader, fact_checker, style_enforcer],\n    llm_factory=OpenAIAugmentedLLM,\n)\n\nresult = await parallel.generate_str(\"Student short story submission: ...\", RequestParams(model=\"gpt4-o\"))\n```\n\n\u003c/details\u003e\n\n### [Router](src/mcp_agent/workflows/router/)\n\n![Router workflow (Image credit: Anthropic)](https://www.anthropic.com/_next/image?url=https%3A%2F%2Fwww-cdn.anthropic.com%2Fimages%2F4zrzovbb%2Fwebsite%2F5c0c0e9fe4def0b584c04d37849941da55e5e71c-2401x1000.png\u0026w=3840\u0026q=75)\n\nGiven an input, route to the `top_k` most relevant categories. A category can be an Agent, an MCP server or a regular function.\n\nmcp-agent provides several router implementations, including:\n\n- [`EmbeddingRouter`](src/mcp_agent/workflows/router/router_embedding.py): uses embedding models for classification\n- [`LLMRouter`](src/mcp_agent/workflows/router/router_llm.py): uses LLMs for classification\n\n\u003e [!NOTE]\n\u003e\n\u003e **[Link to full example](examples/workflows/workflow_router/main.py)**\n\n\u003cdetails\u003e\n\u003csummary\u003eExample\u003c/summary\u003e\n\n```python\ndef print_hello_world:\n     print(\"Hello, world!\")\n\nfinder_agent = Agent(name=\"finder\", server_names=[\"fetch\", \"filesystem\"])\nwriter_agent = Agent(name=\"writer\", server_names=[\"filesystem\"])\n\nllm = OpenAIAugmentedLLM()\nrouter = LLMRouter(\n    llm=llm,\n    agents=[finder_agent, writer_agent],\n    functions=[print_hello_world],\n)\n\nresults = await router.route( # Also available: route_to_agent, route_to_server\n    request=\"Find and print the contents of README.md verbatim\",\n    top_k=1\n)\nchosen_agent = results[0].result\nasync with chosen_agent:\n    ...\n```\n\n\u003c/details\u003e\n\n### [IntentClassifier](src/mcp_agent/workflows/intent_classifier/)\n\nA close sibling of Router, the Intent Classifier pattern identifies the `top_k` Intents that most closely match a given input.\nJust like a Router, mcp-agent provides both an [embedding](src/mcp_agent/workflows/intent_classifier/intent_classifier_embedding.py) and [LLM-based](src/mcp_agent/workflows/intent_classifier/intent_classifier_llm.py) intent classifier.\n\n### [Evaluator-Optimizer](src/mcp_agent/workflows/evaluator_optimizer/evaluator_optimizer.py)\n\n![Evaluator-optimizer workflow (Image credit: Anthropic)](https://www.anthropic.com/_next/image?url=https%3A%2F%2Fwww-cdn.anthropic.com%2Fimages%2F4zrzovbb%2Fwebsite%2F14f51e6406ccb29e695da48b17017e899a6119c7-2401x1000.png\u0026w=3840\u0026q=75)\n\nOne LLM (the “optimizer”) refines a response, another (the “evaluator”) critiques it until a response exceeds a quality criteria.\n\n\u003e [!NOTE]\n\u003e\n\u003e **[Link to full example](examples/workflows/workflow_evaluator_optimizer/main.py)**\n\n\u003cdetails\u003e\n\u003csummary\u003eExample\u003c/summary\u003e\n\n```python\noptimizer = Agent(name=\"cover_letter_writer\", server_names=[\"fetch\"], instruction=\"Generate a cover letter ...\")\nevaluator = Agent(name=\"critiquer\", instruction=\"Evaluate clarity, specificity, relevance...\")\n\nllm = EvaluatorOptimizerLLM(\n    optimizer=optimizer,\n    evaluator=evaluator,\n    llm_factory=OpenAIAugmentedLLM,\n    min_rating=QualityRating.EXCELLENT, # Keep iterating until the minimum quality bar is reached\n)\n\nresult = await eo_llm.generate_str(\"Write a job cover letter for an AI framework developer role at LastMile AI.\")\nprint(\"Final refined cover letter:\", result)\n```\n\n\u003c/details\u003e\n\n### [Orchestrator-workers](src/mcp_agent/workflows/orchestrator/orchestrator.py)\n\n![Orchestrator workflow (Image credit: Anthropic)](https://www.anthropic.com/_next/image?url=https%3A%2F%2Fwww-cdn.anthropic.com%2Fimages%2F4zrzovbb%2Fwebsite%2F8985fc683fae4780fb34eab1365ab78c7e51bc8e-2401x1000.png\u0026w=3840\u0026q=75)\n\nA higher-level LLM generates a plan, then assigns them to sub-agents, and synthesizes the results.\nThe Orchestrator workflow automatically parallelizes steps that can be done in parallel, and blocks on dependencies.\n\n\u003e [!NOTE]\n\u003e\n\u003e **[Link to full example](examples/workflows/workflow_orchestrator_worker/main.py)**\n\n\u003cdetails\u003e\n\u003csummary\u003eExample\u003c/summary\u003e\n\n```python\nfinder_agent = Agent(name=\"finder\", server_names=[\"fetch\", \"filesystem\"])\nwriter_agent = Agent(name=\"writer\", server_names=[\"filesystem\"])\nproofreader = Agent(name=\"proofreader\", ...)\nfact_checker = Agent(name=\"fact_checker\", ...)\nstyle_enforcer = Agent(name=\"style_enforcer\", instructions=\"Use APA style guide from ...\", server_names=[\"fetch\"])\n\norchestrator = Orchestrator(\n    llm_factory=AnthropicAugmentedLLM,\n    available_agents=[finder_agent, writer_agent, proofreader, fact_checker, style_enforcer],\n)\n\ntask = \"Load short_story.md, evaluate it, produce a graded_report.md with multiple feedback aspects.\"\nresult = await orchestrator.generate_str(task, RequestParams(model=\"gpt-4o\"))\nprint(result)\n```\n\n\u003c/details\u003e\n\n### [Swarm](src/mcp_agent/workflows/swarm/swarm.py)\n\nOpenAI has an experimental multi-agent pattern called [Swarm](https://github.com/openai/swarm), which we provide a model-agnostic reference implementation for in mcp-agent.\n\n\u003cimg src=\"https://github.com/openai/swarm/blob/main/assets/swarm_diagram.png?raw=true\" width=500 /\u003e\n\nThe mcp-agent Swarm pattern works seamlessly with MCP servers, and is exposed as an `AugmentedLLM`, allowing for composability with other patterns above.\n\n\u003e [!NOTE]\n\u003e\n\u003e **[Link to full example](examples/workflows/workflow_swarm/main.py)**\n\n\u003cdetails\u003e\n\u003csummary\u003eExample\u003c/summary\u003e\n\n```python\ntriage_agent = SwarmAgent(...)\nflight_mod_agent = SwarmAgent(...)\nlost_baggage_agent = SwarmAgent(...)\n\n# The triage agent decides whether to route to flight_mod_agent or lost_baggage_agent\nswarm = AnthropicSwarm(agent=triage_agent, context_variables={...})\n\ntest_input = \"My bag was not delivered!\"\nresult = await swarm.generate_str(test_input)\nprint(\"Result:\", result)\n```\n\n\u003c/details\u003e\n\n## Advanced\n\n### Composability\n\nAn example of composability is using an [Evaluator-Optimizer](#evaluator-optimizer) workflow as the planner LLM inside\nthe [Orchestrator](#orchestrator-workers) workflow. Generating a high-quality plan to execute is important for robust behavior, and an evaluator-optimizer can help ensure that.\n\nDoing so is seamless in mcp-agent, because each workflow is implemented as an `AugmentedLLM`.\n\n\u003cdetails\u003e\n\u003csummary\u003eExample\u003c/summary\u003e\n\n```python\noptimizer = Agent(name=\"plan_optimizer\", server_names=[...], instruction=\"Generate a plan given an objective ...\")\nevaluator = Agent(name=\"plan_evaluator\", instruction=\"Evaluate logic, ordering and precision of plan......\")\n\nplanner_llm = EvaluatorOptimizerLLM(\n    optimizer=optimizer,\n    evaluator=evaluator,\n    llm_factory=OpenAIAugmentedLLM,\n    min_rating=QualityRating.EXCELLENT,\n)\n\norchestrator = Orchestrator(\n    llm_factory=AnthropicAugmentedLLM,\n    available_agents=[finder_agent, writer_agent, proofreader, fact_checker, style_enforcer],\n    planner=planner_llm # It's that simple\n)\n\n...\n```\n\n\u003c/details\u003e\n\n### Signaling and Human Input\n\n**Signaling**: The framework can pause/resume tasks. The agent or LLM might “signal” that it needs user input, so the workflow awaits. A developer may signal during a workflow to seek approval or review before continuing with a workflow.\n\n**Human Input**: If an Agent has a `human_input_callback`, the LLM can call a `__human_input__` tool to request user input mid-workflow.\n\n\u003cdetails\u003e\n\u003csummary\u003eExample\u003c/summary\u003e\n\nThe [Swarm example](examples/workflows/workflow_swarm/main.py) shows this in action.\n\n```python\nfrom mcp_agent.human_input.handler import console_input_callback\n\nlost_baggage = SwarmAgent(\n    name=\"Lost baggage traversal\",\n    instruction=lambda context_variables: f\"\"\"\n        {\n        FLY_AIR_AGENT_PROMPT.format(\n            customer_context=context_variables.get(\"customer_context\", \"None\"),\n            flight_context=context_variables.get(\"flight_context\", \"None\"),\n        )\n    }\\n Lost baggage policy: policies/lost_baggage_policy.md\"\"\",\n    functions=[\n        escalate_to_agent,\n        initiate_baggage_search,\n        transfer_to_triage,\n        case_resolved,\n    ],\n    server_names=[\"fetch\", \"filesystem\"],\n    human_input_callback=console_input_callback, # Request input from the console\n)\n```\n\n\u003c/details\u003e\n\n### App Config\n\nCreate an [`mcp_agent.config.yaml`](/schema/mcp-agent.config.schema.json) and a gitignored [`mcp_agent.secrets.yaml`](./examples/basic/mcp_basic_agent/mcp_agent.secrets.yaml.example) to define MCP app configuration. This controls logging, execution, LLM provider APIs, and MCP server configuration.\n\n### MCP server management\n\nmcp-agent makes it trivial to connect to MCP servers. Create an [`mcp_agent.config.yaml`](/schema/mcp-agent.config.schema.json) to define server configuration under the `mcp` section:\n\n```yaml\nmcp:\n  servers:\n    fetch:\n      command: \"uvx\"\n      args: [\"mcp-server-fetch\"]\n      description: \"Fetch content at URLs from the world wide web\"\n```\n\n#### [`gen_client`](src/mcp_agent/mcp/gen_client.py)\n\nManage the lifecycle of an MCP server within an async context manager:\n\n```python\nfrom mcp_agent.mcp.gen_client import gen_client\n\nasync with gen_client(\"fetch\") as fetch_client:\n    # Fetch server is initialized and ready to use\n    result = await fetch_client.list_tools()\n\n# Fetch server is automatically disconnected/shutdown\n```\n\nThe gen_client function makes it easy to spin up connections to MCP servers.\n\n#### Persistent server connections\n\nIn many cases, you want an MCP server to stay online for persistent use (e.g. in a multi-step tool use workflow).\nFor persistent connections, use:\n\n- [`connect`](\u003c(src/mcp_agent/mcp/gen_client.py)\u003e) and [`disconnect`](src/mcp_agent/mcp/gen_client.py)\n\n```python\nfrom mcp_agent.mcp.gen_client import connect, disconnect\n\nfetch_client = None\ntry:\n     fetch_client = connect(\"fetch\")\n     result = await fetch_client.list_tools()\nfinally:\n     disconnect(\"fetch\")\n```\n\n- [`MCPConnectionManager`](src/mcp_agent/mcp/mcp_connection_manager.py)\n  For even more fine-grained control over server connections, you can use the MCPConnectionManager.\n\n\u003cdetails\u003e\n\u003csummary\u003eExample\u003c/summary\u003e\n\n```python\nfrom mcp_agent.context import get_current_context\nfrom mcp_agent.mcp.mcp_connection_manager import MCPConnectionManager\n\ncontext = get_current_context()\nconnection_manager = MCPConnectionManager(context.server_registry)\n\nasync with connection_manager:\nfetch_client = await connection_manager.get_server(\"fetch\") # Initializes fetch server\nresult = fetch_client.list_tool()\nfetch_client2 = await connection_manager.get_server(\"fetch\") # Reuses same server connection\n\n# All servers managed by connection manager are automatically disconnected/shut down\n```\n\n\u003c/details\u003e\n\n#### MCP Server Aggregator\n\n[`MCPAggregator`](src/mcp_agent/mcp/mcp_aggregator.py) acts as a \"server-of-servers\".\nIt provides a single MCP server interface for interacting with multiple MCP servers.\nThis allows you to expose tools from multiple servers to LLM applications.\n\n\u003cdetails\u003e\n\u003csummary\u003eExample\u003c/summary\u003e\n\n```python\nfrom mcp_agent.mcp.mcp_aggregator import MCPAggregator\n\naggregator = await MCPAggregator.create(server_names=[\"fetch\", \"filesystem\"])\n\nasync with aggregator:\n   # combined list of tools exposed by 'fetch' and 'filesystem' servers\n   tools = await aggregator.list_tools()\n\n   # namespacing -- invokes the 'fetch' server to call the 'fetch' tool\n   fetch_result = await aggregator.call_tool(name=\"fetch-fetch\", arguments={\"url\": \"https://www.anthropic.com/research/building-effective-agents\"})\n\n   # no namespacing -- first server in the aggregator exposing that tool wins\n   read_file_result = await aggregator.call_tool(name=\"read_file\", arguments={})\n```\n\n\u003c/details\u003e\n\n## Contributing\n\nWe welcome any and all kinds of contributions. Please see the [CONTRIBUTING guidelines](./CONTRIBUTING.md) to get started.\n\n### Special Mentions\n\nThere have already been incredible community contributors who are driving this project forward:\n\n- [Shaun Smith (@evalstate)](https://github.com/evalstate) -- who has been leading the charge on countless complex improvements, both to `mcp-agent` and generally to the MCP ecosystem.\n- [Jerron Lim (@StreetLamb)](https://github.com/StreetLamb) -- who has contributed countless hours and excellent examples, and great ideas to the project.\n- [Jason Summer (@jasonsum)](https://github.com/jasonsum) -- for identifying several issues and adapting his Gmail MCP server to work with mcp-agent\n\n## Roadmap\n\nWe will be adding a detailed roadmap (ideally driven by your feedback). The current set of priorities include:\n\n- **Durable Execution** -- allow workflows to pause/resume and serialize state so they can be replayed or be paused indefinitely. We are working on integrating [Temporal](./src/mcp_agent/executor/temporal.py) for this purpose.\n- **Memory** -- adding support for long-term memory\n- **Streaming** -- Support streaming listeners for iterative progress\n- **Additional MCP capabilities** -- Expand beyond tool calls to support:\n  - Resources\n  - Prompts\n  - Notifications\n\n## FAQs\n\n### What are the core benefits of using mcp-agent?\n\nmcp-agent provides a streamlined approach to building AI agents using capabilities exposed by **MCP** (Model Context Protocol) servers.\n\nMCP is quite low-level, and this framework handles the mechanics of connecting to servers, working with LLMs, handling external signals (like human input) and supporting persistent state via durable execution. That lets you, the developer, focus on the core business logic of your AI application.\n\nCore benefits:\n\n- 🤝 **Interoperability**: ensures that any tool exposed by any number of MCP servers can seamlessly plug in to your agents.\n- ⛓️ **Composability \u0026 Cutstomizability**: Implements well-defined workflows, but in a composable way that enables compound workflows, and allows full customization across model provider, logging, orchestrator, etc.\n- 💻 **Programmatic control flow**: Keeps things simple as developers just write code instead of thinking in graphs, nodes and edges. For branching logic, you write `if` statements. For cycles, use `while` loops.\n- 🖐️ **Human Input \u0026 Signals**: Supports pausing workflows for external signals, such as human input, which are exposed as tool calls an Agent can make.\n\n### Do you need an MCP client to use mcp-agent?\n\nNo, you can use mcp-agent anywhere, since it handles MCPClient creation for you. This allows you to leverage MCP servers outside of MCP hosts like Claude Desktop.\n\nHere's all the ways you can set up your mcp-agent application:\n\n#### MCP-Agent Server\n\nYou can expose mcp-agent applications as MCP servers themselves (see [example](./examples/basic/mcp_agent_server)), allowing MCP clients to interface with sophisticated AI workflows using the standard tools API of MCP servers. This is effectively a server-of-servers.\n\n#### MCP Client or Host\n\nYou can embed mcp-agent in an MCP client directly to manage the orchestration across multiple MCP servers.\n\n#### Standalone\n\nYou can use mcp-agent applications in a standalone fashion (i.e. they aren't part of an MCP client). The [`examples`](/examples/) are all standalone applications.\n\n### Tell me a fun fact\n\nI debated naming this project _silsila_ (سلسلہ), which means chain of events in Urdu. mcp-agent is more matter-of-fact, but there's still an easter egg in the project paying homage to silsila.\n","project_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flastmile-ai%2Fmcp-agent","html_url":"https://awesome.ecosyste.ms/projects/github.com%2Flastmile-ai%2Fmcp-agent","lists_url":"https://awesome.ecosyste.ms/api/v1/projects/github.com%2Flastmile-ai%2Fmcp-agent/lists"}