Debian Codegraph @

examples/mcp_tool_runner.py

raw
1 """Example showing how to use MCP helpers with tool_runner().
2
3 Connects to an MCP server, converts its tools to Anthropic-compatible tools
4 using async_mcp_tool(), and runs them in a tool_runner() loop.
5
6 Requires: pip install anthropic[mcp]
7 Requires: Python 3.10+
8 """
9
10 import asyncio
11
12 import rich
13 from mcp import ClientSession
14 from mcp.client.stdio import StdioServerParameters, stdio_client
15
16 from anthropic import AsyncAnthropic
17 from anthropic.lib.tools.mcp import async_mcp_tool
18
19 client = AsyncAnthropic()
20
21
22 async def main() -> None:
23 # Connect to a local MCP server via stdio
24 # This example uses the MCP filesystem server; replace with your own server
25 server_params = StdioServerParameters(
26 command="npx",
27 args=["-y", "@modelcontextprotocol/server-filesystem", "/tmp"],
28 )
29
30 async with stdio_client(server_params) as (read, write):
31 async with ClientSession(read, write) as mcp_client:
32 await mcp_client.initialize()
33
34 # List available tools from the MCP server and convert them
35 tools_result = await mcp_client.list_tools()
36 tools = [async_mcp_tool(t, mcp_client) for t in tools_result.tools]
37
38 print(f"Connected to MCP server with {len(tools)} tools:")
39 for tool in tools:
40 print(f" - {tool.name}")
41 print()
42
43 # Run a conversation with tool_runner()
44 runner = client.beta.messages.tool_runner(
45 model="claude-sonnet-5",
46 max_tokens=1024,
47 tools=tools,
48 messages=[{"role": "user", "content": "List the files in /tmp"}],
49 )
50 async for message in runner:
51 rich.print(message)
52
53
54 asyncio.run(main())