-
-
Notifications
You must be signed in to change notification settings - Fork 772
Expand file tree
/
Copy pathmcp-security.py
More file actions
79 lines (69 loc) · 2.3 KB
/
mcp-security.py
File metadata and controls
79 lines (69 loc) · 2.3 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
"""
MCP Security Example
Demonstrates security features for MCP transports.
These features help prevent attacks like DNS rebinding.
Features:
- Origin header validation
- DNS rebinding prevention
- Localhost binding for local servers
- Authentication header support
- Secure session ID generation
Protocol: MCP 2025-11-25
"""
# Example code (requires running MCP servers):
#
# from praisonaiagents import Agent, MCP
#
# # Agent with authentication
# agent = Agent(
# name="Secure Assistant",
# tools=MCP(
# "https://api.example.com/mcp",
# headers={"Authorization": "Bearer your-token"}
# )
# )
#
# # WebSocket with auth token
# agent_ws = Agent(
# name="Secure WebSocket Assistant",
# tools=MCP(
# "wss://api.example.com/mcp",
# auth_token="Bearer your-secret-token"
# )
# )
# Using security utilities directly (no server required)
if __name__ == "__main__":
from praisonaiagents.mcp.mcp_security import (
is_valid_origin,
create_auth_header,
generate_secure_session_id,
SecurityConfig
)
print("MCP Security Example")
print("=" * 40)
# Origin validation (DNS rebinding prevention)
print("\n1. Origin Validation:")
allowed = ["localhost", "127.0.0.1", "example.com"]
print(f" Allowed origins: {allowed}")
print(f" 'http://localhost:8080' valid: {is_valid_origin('http://localhost:8080', allowed)}")
print(f" 'https://evil.com' valid: {is_valid_origin('https://evil.com', allowed)}")
# Authentication headers
print("\n2. Authentication Headers:")
bearer = create_auth_header("my-token", auth_type="bearer")
print(f" Bearer: {bearer}")
basic = create_auth_header("user:pass", auth_type="basic")
print(f" Basic: {basic}")
# Secure session IDs
print("\n3. Secure Session IDs:")
session_id = generate_secure_session_id()
print(f" Generated: {session_id}")
print(f" Length: {len(session_id)} chars")
# Security config
print("\n4. Security Configuration:")
config = SecurityConfig(
allowed_origins=["localhost", "example.com"],
require_auth=True
)
print(f" Validate origin: {config.validate_origin}")
print(f" Require auth: {config.require_auth}")
print(f" Bind address: {config.get_bind_address()}")