openai-agents-python/examples/mcp/filesystem_example/main.py
Rohan Mehta de1e9a754d [3/n] Add an MCP stdio example
### Summary:
Spins up a stdio server with some local files, then asks the model questions.

### Test Plan:
Run the example, see it work.
2025-03-25 13:24:18 -04:00

54 lines
1.7 KiB
Python

import asyncio
import os
import shutil
from agents import Agent, Runner, trace
from agents.mcp import MCPServer, MCPServerStdio
async def run(mcp_server: MCPServer):
agent = Agent(
name="Assistant",
instructions="Use the tools to read the filesystem and answer questions based on those files.",
mcp_servers=[mcp_server],
)
# List the files it can read
message = "Read the files and list them."
print(f"Running: {message}")
result = await Runner.run(starting_agent=agent, input=message)
print(result.final_output)
# Ask about books
message = "What is my #1 favorite book?"
print(f"\n\nRunning: {message}")
result = await Runner.run(starting_agent=agent, input=message)
print(result.final_output)
# Ask a question that reads then reasons.
message = "Look at my favorite songs. Suggest one new song that I might like."
print(f"\n\nRunning: {message}")
result = await Runner.run(starting_agent=agent, input=message)
print(result.final_output)
async def main():
current_dir = os.path.dirname(os.path.abspath(__file__))
samples_dir = os.path.join(current_dir, "sample_files")
async with MCPServerStdio(
params={
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", samples_dir],
}
) as server:
with trace(workflow_name="MCP Filesystem Example"):
await run(server)
if __name__ == "__main__":
# Let's make sure the user has npx installed
if not shutil.which("npx"):
raise RuntimeError("npx is not installed. Please install it with `npm install -g npx`.")
asyncio.run(main())