|
| 1 | +--- |
| 2 | +integration: logfire |
| 3 | +--- |
| 4 | +# Model Context Protocol (MCP) |
| 5 | + |
| 6 | + |
| 7 | +**Logfire** supports instrumenting the [MCP Python SDK](https://github.com/modelcontextprotocol/python-sdk) with the [`logfire.instrument_mcp()`][logfire.Logfire.instrument_mcp] method. This works on both the client and server side. If possible, calling this in both the client and server processes is recommended for nice distributed traces. |
| 8 | + |
| 9 | +Below is a simple example. For the client, we use [Pydantic AI](https://ai.pydantic.dev/mcp/client/) (though any MCP client will work) and OpenAI. To use a different LLM provider instead of OpenAI, replace `openai:gpt-4o` in the client script with a different model name supported by Pydantic AI. |
| 10 | + |
| 11 | +First, install the required dependencies: |
| 12 | + |
| 13 | +```bash |
| 14 | +pip install mcp 'pydantic-ai-slim[openai]' |
| 15 | +``` |
| 16 | + |
| 17 | +Next, run the server script below: |
| 18 | + |
| 19 | +```python title="server.py" |
| 20 | +from mcp.server.fastmcp import FastMCP |
| 21 | + |
| 22 | +import logfire |
| 23 | + |
| 24 | +logfire.configure(service_name='server') |
| 25 | +logfire.instrument_mcp() |
| 26 | + |
| 27 | +app = FastMCP() |
| 28 | + |
| 29 | + |
| 30 | +@app.tool() |
| 31 | +def add(a: int, b: int) -> int: |
| 32 | + logfire.info(f'Calculating {a} + {b}') |
| 33 | + return a + b |
| 34 | + |
| 35 | + |
| 36 | +app.run(transport='streamable-http') |
| 37 | +``` |
| 38 | + |
| 39 | +Then run this client script in another terminal: |
| 40 | + |
| 41 | +```python title="agent.py" |
| 42 | +from pydantic_ai import Agent |
| 43 | +from pydantic_ai.mcp import MCPServerStreamableHTTP |
| 44 | + |
| 45 | +import logfire |
| 46 | + |
| 47 | +logfire.configure(service_name='agent') |
| 48 | +logfire.instrument_pydantic_ai() # (1)! |
| 49 | +logfire.instrument_mcp() |
| 50 | + |
| 51 | +server = MCPServerStreamableHTTP('http://localhost:8000/mcp') |
| 52 | +agent = Agent('openai:gpt-4o', toolsets=[server]) |
| 53 | +result = agent.run_sync('What is 7 plus 5?') |
| 54 | +print(result.output) |
| 55 | +``` |
| 56 | + |
| 57 | +1. Instrumenting Pydantic AI is optional, but adds more context to the trace. |
| 58 | + |
| 59 | +You should see a trace like this in Logfire: |
| 60 | + |
| 61 | + |
0 commit comments