|
| 1 | +import asyncio |
| 2 | +import sys |
| 3 | + |
| 4 | +import anthropic |
| 5 | +from anthropic.types import Message, ToolUseBlock |
| 6 | +from mcp import Client, StdioServerParameters |
| 7 | + |
| 8 | +MODEL = "claude-sonnet-5" |
| 9 | +QUESTION = ( |
| 10 | + "What is the latest version of the Jinja2 package? " |
| 11 | + "Answer in one short plain-text sentence." |
| 12 | +) |
| 13 | + |
| 14 | + |
| 15 | +async def discover_tools(client: Client) -> list[dict]: |
| 16 | + discovered = await client.list_tools() |
| 17 | + return [ |
| 18 | + { |
| 19 | + "name": tool.name, |
| 20 | + "description": tool.description, |
| 21 | + "input_schema": tool.input_schema, |
| 22 | + } |
| 23 | + for tool in discovered.tools |
| 24 | + ] |
| 25 | + |
| 26 | + |
| 27 | +def ask_model( |
| 28 | + client: anthropic.Anthropic, |
| 29 | + messages: list[dict], |
| 30 | + tools: list[dict], |
| 31 | + model: str = MODEL, |
| 32 | +) -> Message: |
| 33 | + return client.messages.create( |
| 34 | + model=model, |
| 35 | + max_tokens=1024, |
| 36 | + tools=tools, |
| 37 | + messages=messages, |
| 38 | + ) |
| 39 | + |
| 40 | + |
| 41 | +async def run_tool(client: Client, block: ToolUseBlock) -> str: |
| 42 | + result = await client.call_tool(block.name, block.input) |
| 43 | + return result.content[0].text |
| 44 | + |
| 45 | + |
| 46 | +def tool_result(block: ToolUseBlock, output: str) -> dict: |
| 47 | + return { |
| 48 | + "role": "user", |
| 49 | + "content": [ |
| 50 | + { |
| 51 | + "type": "tool_result", |
| 52 | + "tool_use_id": block.id, |
| 53 | + "content": output, |
| 54 | + }, |
| 55 | + ], |
| 56 | + } |
| 57 | + |
| 58 | + |
| 59 | +async def main(server: StdioServerParameters) -> None: |
| 60 | + async with Client(server) as mcp: |
| 61 | + tools = await discover_tools(mcp) |
| 62 | + |
| 63 | + client = anthropic.Anthropic() |
| 64 | + messages = [{"role": "user", "content": QUESTION}] |
| 65 | + response = ask_model(client, messages, tools) |
| 66 | + for block in response.content: |
| 67 | + if block.type == "tool_use": |
| 68 | + messages.append( |
| 69 | + {"role": "assistant", "content": response.content} |
| 70 | + ) |
| 71 | + output = await run_tool(mcp, block) |
| 72 | + messages.append(tool_result(block, output)) |
| 73 | + final = ask_model(client, messages, tools) |
| 74 | + print(final.content[0].text) |
| 75 | + |
| 76 | + |
| 77 | +if __name__ == "__main__": |
| 78 | + server = StdioServerParameters( |
| 79 | + command=sys.executable, |
| 80 | + args=["server.py"], |
| 81 | + ) |
| 82 | + asyncio.run(main(server)) |
0 commit comments