|
| 1 | +import asyncio |
| 2 | +import os |
| 3 | +import shutil |
| 4 | + |
| 5 | +from agents import Agent, Runner, trace |
| 6 | +from agents.mcp import MCPServer, MCPServerStdio |
| 7 | + |
| 8 | + |
| 9 | +async def run(mcp_server: MCPServer): |
| 10 | + agent = Agent( |
| 11 | + name="Assistant", |
| 12 | + instructions="Use the tools to read the filesystem and answer questions based on those files.", |
| 13 | + mcp_servers=[mcp_server], |
| 14 | + ) |
| 15 | + |
| 16 | + # List the files it can read |
| 17 | + message = "Read the files and list them." |
| 18 | + print(f"Running: {message}") |
| 19 | + result = await Runner.run(starting_agent=agent, input=message) |
| 20 | + print(result.final_output) |
| 21 | + |
| 22 | + # Ask about books |
| 23 | + message = "What is my #1 favorite book?" |
| 24 | + print(f"\n\nRunning: {message}") |
| 25 | + result = await Runner.run(starting_agent=agent, input=message) |
| 26 | + print(result.final_output) |
| 27 | + |
| 28 | + # Ask a question that reads then reasons. |
| 29 | + message = "Look at my favorite songs. Suggest one new song that I might like." |
| 30 | + print(f"\n\nRunning: {message}") |
| 31 | + result = await Runner.run(starting_agent=agent, input=message) |
| 32 | + print(result.final_output) |
| 33 | + |
| 34 | + |
| 35 | +async def main(): |
| 36 | + current_dir = os.path.dirname(os.path.abspath(__file__)) |
| 37 | + samples_dir = os.path.join(current_dir, "sample_files") |
| 38 | + |
| 39 | + async with MCPServerStdio( |
| 40 | + params={ |
| 41 | + "command": "npx", |
| 42 | + "args": ["-y", "@modelcontextprotocol/server-filesystem", samples_dir], |
| 43 | + } |
| 44 | + ) as server: |
| 45 | + with trace(workflow_name="MCP Filesystem Example"): |
| 46 | + await run(server) |
| 47 | + |
| 48 | + |
| 49 | +if __name__ == "__main__": |
| 50 | + # Let's make sure the user has npx installed |
| 51 | + if not shutil.which("npx"): |
| 52 | + raise RuntimeError("npx is not installed. Please install it with `npm install -g npx`.") |
| 53 | + |
| 54 | + asyncio.run(main()) |
0 commit comments