Skip to content

Instantly share code, notes, and snippets.

@Adam-D-Lewis
Last active September 12, 2025 22:07
Show Gist options
  • Select an option

  • Save Adam-D-Lewis/08e555569f35d0b482846d990aca4966 to your computer and use it in GitHub Desktop.

Select an option

Save Adam-D-Lewis/08e555569f35d0b482846d990aca4966 to your computer and use it in GitHub Desktop.
pydantic-mcp-client-server-example.py
# You'll need to save the 2 files separately in the same dir to run.
# mcp-server.py =================================================================================
from pathlib import Path
from mcp.server.fastmcp import FastMCP
server = FastMCP('Pydantic AI Server')
@server.tool()
def sum(a: int, b: int) -> int:
"""Add two numbers"""
return a + b
@server.resource("dir://desktop")
def desktop() -> list[str]:
"""List the files in the user's desktop"""
desktop = Path.home() / "Desktop"
return [str(f) for f in desktop.iterdir()]
@server.prompt("echo")
def echo_prompt(text: str) -> str:
return text
if __name__ == '__main__':
server.run()
# mcp-client.py =================================================================================
import asyncio
import os
import json
from mcp import ClientSession, StdioServerParameters
from mcp.client.stdio import stdio_client
async def client():
server_params = StdioServerParameters(
command='python', args=['scratch-mcp-server.py'],
)
async with stdio_client(server_params) as (read, write):
async with ClientSession(read, write) as session:
await session.initialize()
# list tools
tools = await session.list_tools()
print(f'Available tools are: {tools.model_dump_json(indent=2)}')
# call tool
result = await session.call_tool('sum', {'a': 1, 'b': 2})
print(f'Sum is: {result.content[0].text}')
resource_result = await session.read_resource('dir://desktop')
print(f'Desktop Files are: {resource_result.contents[0].text}')
# now prompt
prompt_result = await session.get_prompt('echo', {'text': 'This text will be echoed back!'})
print(f'Echoed text is: {prompt_result.messages[0].content.text}')
if __name__ == '__main__':
asyncio.run(client())
"""
Available tools are: {
"meta": null,
"nextCursor": null,
"tools": [
{
"name": "sum",
"title": null,
"description": "Add two numbers",
"inputSchema": {
"properties": {
"a": {
"title": "A",
"type": "integer"
},
"b": {
"title": "B",
"type": "integer"
}
},
"required": [
"a",
"b"
],
"title": "sumArguments",
"type": "object"
},
"outputSchema": {
"properties": {
"result": {
"title": "Result",
"type": "integer"
}
},
"required": [
"result"
],
"title": "sumOutput",
"type": "object"
},
"annotations": null,
"meta": null
}
]
}
Sum is: 3
Desktop Files are: [
"/home/my-user/Desktop/New Folder",
]
Echoed text is: This text will be echoed back!
"""
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment