Skip to content

[3/n] Add an MCP stdio example #337

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 1 commit into from
Mar 25, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 26 additions & 0 deletions examples/mcp/filesystem_example/README.md
Original file line number Diff line number Diff line change
@@ -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()`.
54 changes: 54 additions & 0 deletions examples/mcp/filesystem_example/main.py
Original file line number Diff line number Diff line change
@@ -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())
20 changes: 20 additions & 0 deletions examples/mcp/filesystem_example/sample_files/favorite_books.txt
Original file line number Diff line number Diff line change
@@ -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 Sorcerer’s Stone – J.K. Rowling
6. The Great Gatsby – F. Scott Fitzgerald
7. Charlotte’s 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 L’Engle
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
Original file line number Diff line number Diff line change
@@ -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.
10 changes: 10 additions & 0 deletions examples/mcp/filesystem_example/sample_files/favorite_songs.txt
Original file line number Diff line number Diff line change
@@ -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. "Don’t Stop Believin’" – Journey
8. "Dancing Queen" – ABBA
9. "Happy" – Pharrell Williams
10. "Wonderwall" – Oasis