forked from microsoft/agent-governance-toolkit
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmcp_demo.py
More file actions
380 lines (309 loc) · 12 KB
/
mcp_demo.py
File metadata and controls
380 lines (309 loc) · 12 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
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
# Copyright (c) Microsoft Corporation.
# Licensed under the MIT License.
"""
MCP (Model Context Protocol) Integration Demo - Agent Control Plane
This example demonstrates how to use the Agent Control Plane with MCP
to govern tool and resource calls in MCP-compliant servers.
MCP is Anthropic's open standard for connecting AI agents to external tools,
data sources, and services.
"""
import sys
import os
import json
# Add the src directory to the path
sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), "..", "src")))
from agent_control_plane import (
AgentControlPlane,
MCPAdapter,
MCPServer,
create_governed_mcp_server,
ActionType,
PermissionLevel,
)
def print_section(title):
"""Print a formatted section header"""
print("\n" + "=" * 80)
print(f" {title}")
print("=" * 80 + "\n")
def demo_basic_mcp_server():
"""Demonstrate basic MCP server with governance"""
print_section("Demo 1: Basic MCP Server with Governance")
# Create control plane
control_plane = AgentControlPlane()
# Define permissions
permissions = {
ActionType.FILE_READ: PermissionLevel.READ_ONLY,
ActionType.DATABASE_QUERY: PermissionLevel.READ_ONLY,
ActionType.FILE_WRITE: PermissionLevel.NONE, # Blocked!
}
# Create governed MCP server
mcp_server = create_governed_mcp_server(
control_plane=control_plane,
agent_id="mcp-file-server",
server_name="file-server",
permissions=permissions,
transport="stdio"
)
print("✓ Created governed MCP server")
print(f"✓ Server name: file-server")
print(f"✓ Transport: stdio (standard input/output)")
print(f"✓ Permissions: READ_ONLY for files and database")
print(f"✓ File writes: BLOCKED\n")
# Register tools
def handle_read_file(args):
return {"content": f"Mock file content from {args.get('path', 'unknown')}"}
mcp_server.register_tool("read_file", handle_read_file, "Read a file from disk")
print("✓ Registered tool: read_file")
print("✓ All tool calls will be governed by the control plane!")
def demo_mcp_protocol_messages():
"""Demonstrate MCP protocol message handling"""
print_section("Demo 2: MCP Protocol Message Handling")
control_plane = AgentControlPlane()
permissions = {
ActionType.FILE_READ: PermissionLevel.READ_ONLY,
}
agent_context = control_plane.create_agent("mcp-client", permissions)
# Create MCP adapter
adapter = MCPAdapter(
control_plane=control_plane,
agent_context=agent_context
)
# Register a tool
adapter.register_tool("read_file", {
"name": "read_file",
"description": "Read a file from the filesystem",
"inputSchema": {
"type": "object",
"properties": {
"path": {"type": "string"}
}
}
})
print("✓ Created MCP adapter")
print("✓ Registered tool: read_file\n")
# Example 1: tools/list request
print("Example 1: List available tools (tools/list)")
list_request = {
"jsonrpc": "2.0",
"id": 1,
"method": "tools/list",
"params": {}
}
response = adapter.handle_message(list_request)
print(f"Request: {json.dumps(list_request, indent=2)}")
print(f"Response: {json.dumps(response, indent=2)}\n")
# Example 2: tools/call request (allowed)
print("Example 2: Call tool - allowed (tools/call)")
call_request = {
"jsonrpc": "2.0",
"id": 2,
"method": "tools/call",
"params": {
"name": "read_file",
"arguments": {"path": "/data/test.txt"}
}
}
response = adapter.handle_message(call_request)
print(f"Request: {json.dumps(call_request, indent=2)}")
print(f"Response: {json.dumps(response, indent=2)}\n")
print("✓ MCP protocol messages are handled with governance")
print("✓ JSON-RPC 2.0 format for requests and responses")
def demo_mcp_resources():
"""Demonstrate MCP resource handling"""
print_section("Demo 3: MCP Resource Handling")
control_plane = AgentControlPlane()
permissions = {
ActionType.FILE_READ: PermissionLevel.READ_ONLY,
}
agent_context = control_plane.create_agent("mcp-resource-client", permissions)
adapter = MCPAdapter(
control_plane=control_plane,
agent_context=agent_context
)
# Register resources
adapter.register_resource("file://", {
"uri": "file://",
"name": "Local Files",
"description": "Access to local filesystem",
"mimeType": "text/plain"
})
print("✓ Created MCP adapter")
print("✓ Registered resource: file://\n")
# List resources
print("Example 1: List available resources (resources/list)")
list_request = {
"jsonrpc": "2.0",
"id": 1,
"method": "resources/list",
"params": {}
}
response = adapter.handle_message(list_request)
print(f"Response: {json.dumps(response, indent=2)}\n")
# Read a resource
print("Example 2: Read a resource (resources/read)")
read_request = {
"jsonrpc": "2.0",
"id": 2,
"method": "resources/read",
"params": {
"uri": "file:///data/test.txt"
}
}
response = adapter.handle_message(read_request)
print(f"Request: {json.dumps(read_request, indent=2)}")
print(f"Response: {json.dumps(response, indent=2)}\n")
print("✓ MCP resources are governed just like tools")
print("✓ URI-based resource access with permissions")
def demo_mcp_error_handling():
"""Demonstrate MCP error handling for blocked actions"""
print_section("Demo 4: MCP Error Handling - Blocked Actions")
control_plane = AgentControlPlane()
# Restrictive permissions - no write access
permissions = {
ActionType.FILE_READ: PermissionLevel.READ_ONLY,
ActionType.FILE_WRITE: PermissionLevel.NONE, # Blocked!
}
agent_context = control_plane.create_agent("restricted-mcp-client", permissions)
adapter = MCPAdapter(
control_plane=control_plane,
agent_context=agent_context
)
# Register a write tool
adapter.register_tool("write_file", {
"name": "write_file",
"description": "Write to a file",
"inputSchema": {
"type": "object",
"properties": {
"path": {"type": "string"},
"content": {"type": "string"}
}
}
})
print("✓ Created MCP adapter with restricted permissions")
print("✓ File writes: BLOCKED\n")
# Try to call the blocked tool
print("Example: Attempt to write file (BLOCKED)")
write_request = {
"jsonrpc": "2.0",
"id": 1,
"method": "tools/call",
"params": {
"name": "write_file",
"arguments": {
"path": "/data/output.txt",
"content": "This should be blocked"
}
}
}
response = adapter.handle_message(write_request)
print(f"Request: {json.dumps(write_request, indent=2)}")
print(f"Response: {json.dumps(response, indent=2)}\n")
print("✓ Blocked actions return JSON-RPC error responses")
print("✓ Error code -32000 for permission errors")
print("✓ Clear error messages for debugging")
def demo_integration_pattern():
"""Demonstrate real-world MCP integration"""
print_section("Demo 5: Real-World MCP Integration Pattern")
print("Real-world MCP server integration pattern:\n")
print("1. Server Setup:")
print(" ```python")
print(" from agent_control_plane import create_governed_mcp_server")
print(" ")
print(" # Create governed MCP server")
print(" mcp_server = create_governed_mcp_server(")
print(" control_plane=control_plane,")
print(" agent_id='production-mcp-server',")
print(" server_name='company-data-server',")
print(" permissions={")
print(" ActionType.FILE_READ: PermissionLevel.READ_ONLY,")
print(" ActionType.DATABASE_QUERY: PermissionLevel.READ_ONLY,")
print(" },")
print(" transport='stdio'")
print(" )")
print(" ```\n")
print("2. Register Tools and Resources:")
print(" ```python")
print(" # Register tools")
print(" mcp_server.register_tool('read_file', handle_read_file,")
print(" 'Read files from disk')")
print(" mcp_server.register_tool('query_db', handle_query_db,")
print(" 'Query the database')")
print(" ")
print(" # Register resources")
print(" mcp_server.register_resource('file://', handle_file_resource,")
print(" 'Access to local files')")
print(" mcp_server.register_resource('db://', handle_db_resource,")
print(" 'Database access')")
print(" ```\n")
print("3. Start Server:")
print(" ```python")
print(" # Start the MCP server")
print(" mcp_server.start()")
print(" ")
print(" # Process incoming MCP requests")
print(" while True:")
print(" request = receive_mcp_request() # From stdio, SSE, etc.")
print(" response = mcp_server.handle_request(request)")
print(" send_mcp_response(response)")
print(" ```\n")
print("4. Benefits:")
print(" ✓ Standard MCP protocol compliance")
print(" ✓ All tools and resources governed")
print(" ✓ Works with any MCP-compatible client")
print(" ✓ Complete audit trail")
print(" ✓ Easy integration with Claude, IDEs, etc.")
def demo_mcp_features():
"""Demonstrate MCP protocol features"""
print_section("Demo 6: MCP Protocol Features")
print("MCP (Model Context Protocol) Features:\n")
print("1. Tools (Function Calling):")
print(" - Expose functions to AI agents")
print(" - Input schema validation")
print(" - Governed execution\n")
print("2. Resources (Data Access):")
print(" - URI-based resource access")
print(" - Multiple resource types (files, databases, APIs)")
print(" - Read operations with governance\n")
print("3. Prompts (Templated Prompts):")
print(" - Pre-defined prompt templates")
print(" - Consistent agent behavior")
print(" - Safe prompt management\n")
print("4. JSON-RPC 2.0:")
print(" - Standard protocol format")
print(" - Request/response structure")
print(" - Error handling\n")
print("5. Transports:")
print(" - stdio: Standard input/output")
print(" - SSE: Server-Sent Events")
print(" - HTTP: REST API\n")
print("✓ Agent Control Plane governs all MCP operations")
print("✓ Same governance approach across all transports")
print("✓ Compatible with any MCP-compliant client")
def main():
"""Run all demos"""
print("\n" + "=" * 80)
print(" MCP (Model Context Protocol) Integration Demo")
print("=" * 80)
try:
demo_basic_mcp_server()
demo_mcp_protocol_messages()
demo_mcp_resources()
demo_mcp_error_handling()
demo_integration_pattern()
demo_mcp_features()
print_section("Summary")
print("✓ MCP adapter provides governance for MCP protocol")
print("✓ Standard JSON-RPC 2.0 message handling")
print("✓ Tools and resources are governed")
print("✓ Error responses for blocked actions")
print("✓ Compatible with any MCP client")
print("\n✓ Use MCP to connect agents to external tools")
print("✓ Agent Control Plane ensures safe execution!")
print("\n" + "=" * 80 + "\n")
except Exception as e:
print(f"\n❌ Error: {str(e)}")
import traceback
traceback.print_exc()
if __name__ == "__main__":
main()