[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.
This commit is contained in:
Rohan Mehta 2025-03-25 13:24:18 -04:00
parent 4f8cbfa676
commit de1e9a754d
5 changed files with 114 additions and 0 deletions

View file

@ -0,0 +1,26 @@
# MCP Filesystem Example
This example uses the [fileystem MCP server](https://github.com/modelcontextprotocol/servers/tree/main/src/filesystem), running locally via `npx`.
Run it via:
```
uv run python python examples/mcp/filesystem_example/main.py
```
## Details
The example uses the `MCPServerStdio` class from `agents`, with the command:
```bash
npx -y "@modelcontextprotocol/server-filesystem" <samples_directory>
```
It's only given access to the `sample_files` directory adjacent to the example, which contains some sample data.
Under the hood:
1. The server is spun up in a subprocess, and exposes a bunch of tools like `list_directory()`, `read_file()`, etc.
2. We add the server instance to the Agent via `mcp_agents`.
3. Each time the agent runs, we call out to the MCP server to fetch the list of tools via `server.list_tools()`.
4. If the LLM chooses to use an MCP tool, we call the MCP server to run the tool via `server.run_tool()`.

View file

@ -0,0 +1,54 @@
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())

View file

@ -0,0 +1,20 @@
1. To Kill a Mockingbird Harper Lee
2. Pride and Prejudice Jane Austen
3. 1984 George Orwell
4. The Hobbit J.R.R. Tolkien
5. Harry Potter and the Sorcerers Stone J.K. Rowling
6. The Great Gatsby F. Scott Fitzgerald
7. Charlottes Web E.B. White
8. Anne of Green Gables Lucy Maud Montgomery
9. The Alchemist Paulo Coelho
10. Little Women Louisa May Alcott
11. The Catcher in the Rye J.D. Salinger
12. Animal Farm George Orwell
13. The Chronicles of Narnia: The Lion, the Witch, and the Wardrobe C.S. Lewis
14. The Book Thief Markus Zusak
15. A Wrinkle in Time Madeleine LEngle
16. The Secret Garden Frances Hodgson Burnett
17. Moby-Dick Herman Melville
18. Fahrenheit 451 Ray Bradbury
19. Jane Eyre Charlotte Brontë
20. The Little Prince Antoine de Saint-Exupéry

View file

@ -0,0 +1,4 @@
- In the summer, I love visiting London.
- In the winter, Tokyo is great.
- In the spring, San Francisco.
- In the fall, New York is the best.

View file

@ -0,0 +1,10 @@
1. "Here Comes the Sun" The Beatles
2. "Imagine" John Lennon
3. "Bohemian Rhapsody" Queen
4. "Shake It Off" Taylor Swift
5. "Billie Jean" Michael Jackson
6. "Uptown Funk" Mark Ronson ft. Bruno Mars
7. "Dont Stop Believin" Journey
8. "Dancing Queen" ABBA
9. "Happy" Pharrell Williams
10. "Wonderwall" Oasis