MCPServerHTTP requires an MCP server to be running and accepting HTTP connections before calling agent.run_mcp_servers(). Running the server is not managed by PydanticAI.
The name "HTTP" is used since this implemented will be adapted in future to use the new
Streamable HTTP currently in development.
Before creating the SSE client, we need to run the server (docs here):
frompydantic_aiimportAgentfrompydantic_ai.mcpimportMCPServerHTTPserver=MCPServerHTTP(url='http://localhost:3001/sse')agent=Agent('openai:gpt-4o',mcp_servers=[server])asyncdefmain():asyncwithagent.run_mcp_servers():result=awaitagent.run('How many days between 2000-01-01 and 2025-03-18?')print(result.output)#> There are 9,208 days between January 1, 2000, and March 18, 2025.
(This example is complete, it can be run "as is" with Python 3.10+ — you'll need to add asyncio.run(main()) to run main)
What's happening here?
The model is receiving the prompt "how many days between 2000-01-01 and 2025-03-18?"
The model decides "Oh, I've got this run_python_code tool, that will be a good way to answer this question", and writes some python code to calculate the answer.
The model returns a tool call
PydanticAI sends the tool call to the MCP server using the SSE transport
The model is called again with the return value of running the code
The model returns the final answer
You can visualise this clearly, and even see the code that's run by adding three lines of code to instrument the example with logfire:
The other transport offered by MCP is the stdio transport where the server is run as a subprocess and communicates with the client over stdin and stdout. In this case, you'd use the MCPServerStdio class.
frompydantic_aiimportAgentfrompydantic_ai.mcpimportMCPServerStdioserver=MCPServerStdio('deno',args=['run','-N','-R=node_modules','-W=node_modules','--node-modules-dir=auto','jsr:@pydantic/mcp-run-python','stdio',])agent=Agent('openai:gpt-4o',mcp_servers=[server])asyncdefmain():asyncwithagent.run_mcp_servers():result=awaitagent.run('How many days between 2000-01-01 and 2025-03-18?')print(result.output)#> There are 9,208 days between January 1, 2000, and March 18, 2025.