forked from davehague/mcp-talk
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path01_python_client_demo.py
More file actions
156 lines (131 loc) Β· 6.08 KB
/
01_python_client_demo.py
File metadata and controls
156 lines (131 loc) Β· 6.08 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
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
# Simple MCP Python Client Demo with LLM Integration
# This demonstrates connecting to an MCP server and letting an LLM use its tools
import asyncio
import json
from contextlib import AsyncExitStack
from mcp import ClientSession
from mcp.client.stdio import stdio_client, StdioServerParameters
from openai import OpenAI
async def main():
"""
Simple demo showing how to connect to an MCP server via Python
and interact with its tools and resources.
"""
async with AsyncExitStack() as stack:
# Connect to a local MCP server (filesystem server example)
# In practice, this could be any MCP server: stdio, SSE, or HTTP
server_params = StdioServerParameters(
command="npx",
args=[
"-y",
"@modelcontextprotocol/server-filesystem",
"/Users/davidhague/Downloads",
],
)
transport = await stack.enter_async_context(stdio_client(server_params))
# Create client session
read_stream, write_stream = transport
session = await stack.enter_async_context(
ClientSession(read_stream, write_stream)
)
# Initialize connection
await session.initialize()
print("π Connected to MCP server!")
print("=" * 50)
# 1. List available tools
tools_result = await session.list_tools()
print(f"π Available tools ({len(tools_result.tools)}):")
for tool in tools_result.tools:
print(f" β’ {tool.name}: {tool.description}")
print()
# 2. List available resources
try:
resources_result = await session.list_resources()
print(f"π Available resources ({len(resources_result.resources)}):")
for resource in resources_result.resources:
print(f" β’ {resource.uri}: {resource.name}")
except Exception as e:
print(f"π No resources available: {e}")
print()
# 3. Demo: Let LLM use MCP tools
if tools_result.tools:
print("π€ Letting LLM use MCP tools...")
# Convert MCP tools to OpenAI tool format
openai_tools = []
for tool in tools_result.tools:
openai_tools.append(
{
"type": "function",
"function": {
"name": tool.name,
"description": tool.description,
"parameters": tool.inputSchema
or {"type": "object", "properties": {}},
},
}
)
# Ask LLM to create and manage files
client = OpenAI() # Make sure OPENAI_API_KEY is set
try:
response = client.chat.completions.create(
model="gpt-4o",
messages=[
{
"role": "user",
"content": "Create a file called '/Users/davidhague/Downloads/llm_demo.txt' with a creative message about AI and MCP working together. Then read it back to confirm it was created.",
}
],
tools=openai_tools,
tool_choice="auto",
)
print("\n--- LLM Request Sent ---")
print(f"Messages: {response.choices[0].message.content}")
print(f"Tool Calls: {response.choices[0].message.tool_calls}")
print("--- End LLM Request ---")
# Execute any tool calls the LLM wants to make
message = response.choices[0].message
print(f"\n--- LLM Response Received ---")
print(f"Message: {message.content}")
print(f"Tool Calls: {message.tool_calls}")
print("--- End LLM Response ---")
if message.tool_calls:
print(f"\nπ§ LLM wants to use {len(message.tool_calls)} tool(s):")
for tool_call in message.tool_calls:
print(f" β’ {tool_call.function.name}")
# Execute the tool call via MCP
arguments = json.loads(tool_call.function.arguments)
result = await session.call_tool(
tool_call.function.name, arguments=arguments
)
print(
f" Result: {result.content[0].text if result.content else 'Success!'}"
)
# If it was a read operation, show some content
if tool_call.function.name == "read_file" and result.content:
content = result.content[0].text
preview = (
content[:150] + "..." if len(content) > 150 else content
)
print(f" Content preview: {preview}")
else:
print(f"π¬ LLM response: {message.content}")
except Exception as e:
print(f"β LLM integration failed: {e}")
print(" (Make sure OPENAI_API_KEY is set)")
# Fallback to direct MCP tool usage
print("\nπ Falling back to direct MCP usage...")
if any(tool.name == "write_file" for tool in tools_result.tools):
result = await session.call_tool(
"write_file",
arguments={
"path": "/Users/davidhague/Downloads/mcp_demo.txt",
"content": "Hello from MCP! This file was created via the Model Context Protocol.",
},
)
print(
f" File created: {result.content[0].text if result.content else 'Success!'}"
)
print()
print("\nβ
MCP Demo completed!")
if __name__ == "__main__":
asyncio.run(main())