-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathexample_usage.py
More file actions
73 lines (62 loc) · 2.38 KB
/
example_usage.py
File metadata and controls
73 lines (62 loc) · 2.38 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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
#!/usr/bin/env python
"""
Example demonstrating how to use the Code MCP server programmatically.
This shows how an AI agent would interact with the MCP server to execute code.
"""
import asyncio
import json
from mcp.client import ClientSession
from mcp.client.stdio import stdio_client
async def main():
# Connect to the MCP server via stdio
async with stdio_client() as (read_stream, write_stream):
async with ClientSession(read_stream, write_stream) as session:
# Initialize the session
await session.initialize()
# List available tools
tools = await session.list_tools()
print("Available tools:")
for tool in tools:
print(f" - {tool.name}: {tool.description}")
# Example 1: Execute Python code
print("\n--- Python Example ---")
result = await session.call_tool(
"run_code",
arguments={
"code": "print('Hello from Python!')\nprint(2 + 2)",
"language": "python"
}
)
print(f"Result: {result[0].text}")
# Example 2: Execute JavaScript code
print("\n--- JavaScript Example ---")
result = await session.call_tool(
"run_code",
arguments={
"code": "console.log('Hello from JavaScript!');\nconsole.log(6 * 7);",
"language": "javascript"
}
)
print(f"Result: {result[0].text}")
# Example 3: Execute Bash code
print("\n--- Bash Example ---")
result = await session.call_tool(
"run_code",
arguments={
"code": "echo 'Hello from Bash!'\necho $((3 + 4))",
"language": "bash"
}
)
print(f"Result: {result[0].text}")
# Example 4: Handle errors
print("\n--- Error Handling Example ---")
result = await session.call_tool(
"run_code",
arguments={
"code": "print('Unclosed string",
"language": "python"
}
)
print(f"Result: {result[0].text}")
if __name__ == "__main__":
asyncio.run(main())