forked from mcp-use/mcp-use
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode_mode_example.py
More file actions
55 lines (40 loc) · 1.39 KB
/
code_mode_example.py
File metadata and controls
55 lines (40 loc) · 1.39 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
"""
Code Mode Example - Using MCP Tools via Code Execution
This example demonstrates how AI agents can use MCP tools through code execution mode,
which enables more efficient context usage and data processing compared to
direct tool calls.
Based on Anthropic's research: https://www.anthropic.com/engineering/code-execution-with-mcp
"""
import asyncio
from langchain_anthropic import ChatAnthropic
from mcp_use import MCPAgent, MCPClient
from mcp_use.client.prompts import CODE_MODE_AGENT_PROMPT
# Example configuration with a simple MCP server
# You can replace this with your own server configuration
config = {
"mcpServers": {
"filesystem": {
"command": "npx",
"args": ["-y", "@modelcontextprotocol/server-filesystem", "."],
}
}
}
async def main():
"""Example 5: AI Agent using code mode (requires OpenAI API key)."""
client = MCPClient(config=config, code_mode=True)
# Create LLM
llm = ChatAnthropic(model="claude-haiku-4-5-20251001")
# Create agent with code mode instructions
agent = MCPAgent(
llm=llm,
client=client,
system_prompt=CODE_MODE_AGENT_PROMPT,
max_steps=50,
pretty_print=True,
)
# Example query
query = """ Please list all the files in the current folder."""
async for _ in agent.stream_events(query):
pass
if __name__ == "__main__":
asyncio.run(main())