mirror of
https://github.com/mcp-use/mcp-use.git
synced 2026-09-14 18:06:01 +08:00
8348c59a53
* docs: reorganize navigation and clean up content - Remove 'Misc' group with misplaced blog posts - Remove 'Libraries' redirect group from Home nav - Simplify 'Dev Tools' group (flatten Inspector, CLI, Tunneling) - Remove individual changelog versions from Python nav (keep summary) - Remove changelog from TypeScript 'Get Started' group - Remove tunneling duplicate from Python Development group - Rewrite mcp101 as clean MCP concepts page (was pitch deck) - Delete typescript/blog posts (not technical docs) - Add redirects for deleted blog post URLs * docs: fix content accuracy and remove sloppy language - Fix broken python/server/mcp-apps link in home page - Remove informal pitch-speak from python/server/index.mdx - Fix grammar error in typescript/server/index.mdx - Update typescript/client/logging.mdx: remove fake 'coming soon' API code - Fix non-existent model name gpt-5.1 in typescript quickstart - Fix mcp_use naming in development contributing guide * docs: fix incorrect TypeScript server API calls in inspector docs - Replace server.addTool() with server.tool() (correct mcp-use API) - Add missing zod import to debugging-chatgpt-apps example * docs: fix fake model names (gpt-5.1 → gpt-4o) in agent docs * docs: update model names, fix APIs, and add agent visibility hints - Replace all deprecated model names with latest: gpt-4.1, gpt-4.1-mini, claude-sonnet-4-6, claude-opus-4-7, gemini-2.5-flash across all docs - Fix TypeScript server.tool() API in installation.mdx (old positional string form) - Fix TypeScript agent.run() in quickstart.mdx (deprecated string form → object) - Remove broken manufact.com/docs/llms.txt hidden hints from 5 pages - Add <Visibility for="agents"> block to mcp101.mdx with install commands, key classes, and API signatures for agent-oriented navigation - Add LangChain provider install note to Python quickstart (mcp-use agent requires a separate langchain-* provider package) - Update model name cards in Python llm-integration.mdx * docs: clean up remaining stale model names and improve accuracy - Update supported model lists in Python and TypeScript llm-integration pages - Fix cost optimization table to use current model IDs - Update TypeScript agent overview supported providers list * docs: add LangChain provider install to TypeScript quickstart agent section The MCPAgent requires a separate @langchain/* provider package; this was not mentioned before the code example that imports from @langchain/openai. * docs: update to latest flagship model IDs (May 2026) - OpenAI: gpt-4.1 → gpt-5.5, gpt-4.1-mini → gpt-5.5-mini - Google: gemini-2.5-flash → gemini-3.1-flash, gemini-2.5-pro → gemini-3.1-pro - Groq: llama-3.1-* → llama-4-scout-17b-16e-instruct - Anthropic (claude-opus-4-7, claude-sonnet-4-6) already current, no change * docs: replace all em dashes with hyphens * docs: restore llms.txt hints using Visibility component * docs: simplify TypeScript logging page to unsupported notice only * docs: rewrite mcp101 to explain MCP protocol with mcp-use examples and doc links * docs: remove goal.md * docs: revert nav changes, keep only Misc group removal and blog redirects * docs: reorder mcp101 to Server/App -> Client/Inspector -> Agent, restore title * docs: add code examples for Resources and Prompts in mcp101 * docs: remove em dashes from mcp101 * docs: add MCPClient code examples to mcp101 * docs: add React client example to mcp101 * docs: add agent code examples to mcp101 * docs: expand MCP Apps section in mcp101 with example and links * docs: restore Contacts, Socials, and Founders sections to mcp101 * docs: add context-setting intro paragraph to mcp101 for new readers * docs: add MCP stores section to mcp101 intro with Claude, ChatGPT, Cursor * docs: fix Claude store link * docs: fix ChatGPT store link * docs: fix Cursor store link * docs: replace store Cards with linked image grid * docs: add captions to store images * docs: add Notifications to client primitives table in mcp101 * docs: add lead-in paragraph before resource cards at bottom of mcp101 * docs: move resource cards to end of page after Contacts/Socials/Founders * docs: demote Contacts/Socials/Founders to bold text to remove from TOC * docs: move Contacts/Socials/Founders to very end of mcp101 * docs: add Resources and Contacts section headers, link official MCP docs * chore(docs): update site metadata, footer links, and rename mcp_use to mcp-use * update docs metadata + images * docs: enhance MCP section by highlighting the reach of MCP stores with 1 billion weekly active users * api ref
235 lines
7.7 KiB
Plaintext
235 lines
7.7 KiB
Plaintext
---
|
|
title: Building Custom Agents
|
|
description: Learn how to build custom agents using MCPClient and integrate tools with different agent frameworks
|
|
icon: "paintbrush"
|
|
---
|
|
|
|
MCP-Use provides flexible options for building custom agents that can utilize MCP tools. This guide will show you how to create your own agents by leveraging the existing adapters, particularly focusing on the LangChain adapter.
|
|
|
|
<Info>
|
|
**Why Build Custom Agents?** While MCP-Use provides a built-in `MCPAgent` class, custom agents give you maximum flexibility to integrate with existing systems, implement specialized behavior, or use different agent frameworks.
|
|
</Info>
|
|
|
|
## Overview
|
|
|
|
MCP-Use allows you to:
|
|
|
|
<CardGroup cols={3}>
|
|
<Card title="Access Tools" icon="plug">
|
|
Connect to powerful MCP tools through flexible connectors
|
|
</Card>
|
|
<Card title="Convert & Adapt" icon="arrows-rotate">
|
|
Transform MCP tools to work with any agent framework via adapters
|
|
</Card>
|
|
<Card title="Build Agents" icon="robot">
|
|
Create specialized agents tailored to your specific use cases
|
|
</Card>
|
|
</CardGroup>
|
|
|
|
## Using the LangChain Adapter
|
|
|
|
The `LangChainAdapter` is a powerful component that converts MCP tools to LangChain tools, enabling you to use MCP tools with any LangChain-compatible agent.
|
|
|
|
<Note>
|
|
**Simplified API**: The LangChain adapter provides a streamlined API that handles all the complexity of session management, connector initialization, and tool conversion automatically.
|
|
</Note>
|
|
|
|
### Basic Example
|
|
|
|
Here's a simple example of creating a custom agent using the LangChain adapter:
|
|
|
|
<CodeGroup>
|
|
```python Python
|
|
import asyncio
|
|
from langchain.agents import create_agent
|
|
from langchain.chat_models import init_chat_model
|
|
|
|
from mcp_use.client import MCPClient
|
|
from mcp_use.adapters import LangChainAdapter
|
|
|
|
async def main():
|
|
# Initialize the MCP client
|
|
client = MCPClient.from_config_file("path/to/config.json")
|
|
|
|
# Create adapter instance
|
|
adapter = LangChainAdapter()
|
|
|
|
# Get LangChain tools directly from the client with a single line
|
|
tools = await adapter.create_tools(client)
|
|
|
|
# Initialize your language model
|
|
model = init_chat_model("gpt-5.5", temperature=0.5)
|
|
|
|
# Create the agent
|
|
agent = create_agent(
|
|
model=model,
|
|
tools=tools,
|
|
system_prompt="You are a helpful assistant with access to powerful tools.",
|
|
)
|
|
|
|
# Run the agent
|
|
result = await agent.ainvoke(
|
|
{"messages": [{"role": "user", "content": "What can you do?"}]}
|
|
)
|
|
print(result)
|
|
|
|
if __name__ == "__main__":
|
|
asyncio.run(main())
|
|
```
|
|
</CodeGroup>
|
|
|
|
<Tip>
|
|
**One-Line Tool Creation**: The API simplifies tool creation - all you need is to create an adapter instance and call its `create_tools` method:
|
|
|
|
<CodeGroup>
|
|
```python Python
|
|
adapter = LangChainAdapter()
|
|
tools = await adapter.create_tools(client)
|
|
```
|
|
</CodeGroup>
|
|
|
|
You don't need to worry about sessions, connectors, or initialization. The adapter handles everything for you.
|
|
</Tip>
|
|
|
|
## Contributing New Adapters
|
|
|
|
<Info>
|
|
MCP-Use welcomes contributions for integrating with different agent frameworks! The adapter architecture is designed to make this process straightforward and requires minimal implementation effort.
|
|
</Info>
|
|
|
|
### Adapter Architecture
|
|
|
|
MCP-Use provides a `BaseAdapter` abstract class that handles most of the common functionality:
|
|
|
|
<CardGroup cols={2}>
|
|
<Card title="Automatic Handling" icon="magic">
|
|
- Tool caching management
|
|
- Connector initialization
|
|
- Multi-connector iteration
|
|
</Card>
|
|
<Card title="Simple Implementation" icon="code">
|
|
Only implement `_convert_tool` method to convert MCP tools to your framework's format
|
|
</Card>
|
|
</CardGroup>
|
|
|
|
<Warning>
|
|
**Single Required Method**: To create an adapter for a new framework, you only need to implement one method: `_convert_tool` to convert a single MCP tool to your framework's tool format.
|
|
</Warning>
|
|
|
|
### Creating a New Adapter
|
|
|
|
Here's a simple template for creating a new adapter:
|
|
|
|
```python
|
|
from typing import Any
|
|
|
|
from mcp_use.adapters.base import BaseAdapter
|
|
from mcp_use.connectors.base import BaseConnector
|
|
from your_framework import YourFrameworkTool # Import your framework's tool class
|
|
|
|
class YourFrameworkAdapter(BaseAdapter):
|
|
"""Adapter for converting MCP tools to YourFramework tools."""
|
|
|
|
def _convert_tool(self, mcp_tool: dict[str, Any], connector: BaseConnector) -> YourFrameworkTool:
|
|
"""Convert an MCP tool to your framework's tool format.
|
|
|
|
Args:
|
|
mcp_tool: The MCP tool to convert.
|
|
connector: The connector that provides this tool.
|
|
|
|
Returns:
|
|
A tool in your framework's format, or None if conversion failed.
|
|
"""
|
|
try:
|
|
# Implement your framework-specific conversion logic
|
|
converted_tool = YourFrameworkTool(
|
|
name=mcp_tool.name,
|
|
description=mcp_tool.description,
|
|
# Map the MCP tool properties to your framework's tool properties
|
|
# You might need custom handling for argument schemas, function execution, etc.
|
|
)
|
|
|
|
return converted_tool
|
|
except Exception as e:
|
|
self.logger.error(f"Error converting tool {mcp_tool.name}: {e}")
|
|
return None
|
|
```
|
|
|
|
### Using Your Custom Adapter
|
|
|
|
Once you've implemented your adapter, you can use it with the simplified API:
|
|
|
|
<CodeGroup>
|
|
```python Python
|
|
from your_module import YourFrameworkAdapter
|
|
from mcp_use.client import MCPClient
|
|
|
|
# Initialize the client
|
|
client = MCPClient.from_config_file("config.json")
|
|
|
|
# Create an adapter instance
|
|
adapter = YourFrameworkAdapter()
|
|
|
|
# Get tools with a single line
|
|
tools = await adapter.create_tools(client)
|
|
|
|
# Use the tools with your framework
|
|
agent = your_framework.create_agent(tools=tools)
|
|
```
|
|
</CodeGroup>
|
|
|
|
### Tips for Implementing an Adapter
|
|
|
|
<AccordionGroup>
|
|
<Accordion title="Schema Conversion">
|
|
Most frameworks have their own way of handling argument schemas. You'll need to convert the MCP tool's JSON Schema to your framework's format.
|
|
|
|
<Tip>
|
|
Look at the LangChain adapter implementation as a reference for handling schema conversion patterns.
|
|
</Tip>
|
|
</Accordion>
|
|
|
|
<Accordion title="Tool Execution">
|
|
When a tool is called in your framework, you'll need to pass the call to the connector's `call_tool` method and handle the result.
|
|
|
|
<Warning>
|
|
Always ensure proper async/await handling when calling MCP tools, as they are inherently asynchronous.
|
|
</Warning>
|
|
</Accordion>
|
|
|
|
<Accordion title="Result Parsing">
|
|
MCP tools return structured data with types like text, images, or embedded resources. Your adapter should parse these into a format your framework understands.
|
|
</Accordion>
|
|
|
|
<Accordion title="Error Handling">
|
|
Ensure your adapter handles errors gracefully, both during tool conversion and execution.
|
|
|
|
<Note>
|
|
The base adapter provides logging utilities to help with error reporting and debugging.
|
|
</Note>
|
|
</Accordion>
|
|
</AccordionGroup>
|
|
|
|
|
|
## Conclusion
|
|
|
|
<CardGroup cols={2}>
|
|
<Card title="Maximum Flexibility" icon="expand">
|
|
Build specialized agents tailored to your specific tasks or integrate MCP capabilities into existing systems
|
|
</Card>
|
|
<Card title="Simple Architecture" icon="puzzle-piece">
|
|
Easy extension with minimal implementation - just one `_convert_tool` method needed
|
|
</Card>
|
|
</CardGroup>
|
|
|
|
<Info>
|
|
**Key Benefits:**
|
|
- **Simplified API**: Create tools directly from MCPClient with a single method call
|
|
- **Automatic Management**: Session and connector complexity is handled automatically
|
|
- **Flexible Integration**: Works with any agent framework that has a LangChain-style interface
|
|
</Info>
|
|
|
|
<Tip>
|
|
**Contributing Back**: We welcome contributions to expand the adapter ecosystem! If you develop an adapter for a new framework, please consider contributing it back to the project to help the community.
|
|
</Tip>
|