-
Notifications
You must be signed in to change notification settings - Fork 3.7k
Expand file tree
/
Copy pathserver.py
More file actions
83 lines (70 loc) · 2.65 KB
/
Copy pathserver.py
File metadata and controls
83 lines (70 loc) · 2.65 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
import anyio
import click
import httpx
import mcp_types as types
from mcp.server import Server, ServerRequestContext
async def fetch_website(
url: str,
) -> list[types.ContentBlock]:
headers = {"User-Agent": "MCP Test Server (github.com/modelcontextprotocol/python-sdk)"}
# A general-purpose web fetch wants ordinary browser-like redirect
# behavior; create_mcp_http_client is for talking to a configured MCP
# endpoint and only follows same-origin redirects.
async with httpx.AsyncClient(headers=headers, follow_redirects=True, timeout=30.0) as client:
response = await client.get(url)
response.raise_for_status()
return [types.TextContent(type="text", text=response.text)]
async def handle_list_tools(
ctx: ServerRequestContext, params: types.PaginatedRequestParams | None
) -> types.ListToolsResult:
return types.ListToolsResult(
tools=[
types.Tool(
name="fetch",
title="Website Fetcher",
description="Fetches a website and returns its content",
input_schema={
"type": "object",
"required": ["url"],
"properties": {
"url": {
"type": "string",
"description": "URL to fetch",
}
},
},
)
]
)
async def handle_call_tool(ctx: ServerRequestContext, params: types.CallToolRequestParams) -> types.CallToolResult:
if params.name != "fetch":
raise ValueError(f"Unknown tool: {params.name}")
arguments = params.arguments or {}
if "url" not in arguments:
raise ValueError("Missing required argument 'url'")
content = await fetch_website(arguments["url"])
return types.CallToolResult(content=content)
@click.command()
@click.option("--port", default=8000, help="Port to listen on for HTTP")
@click.option(
"--transport",
type=click.Choice(["stdio", "streamable-http"]),
default="stdio",
help="Transport type",
)
def main(port: int, transport: str) -> int:
app = Server(
"mcp-website-fetcher",
on_list_tools=handle_list_tools,
on_call_tool=handle_call_tool,
)
if transport == "streamable-http":
import uvicorn
uvicorn.run(app.streamable_http_app(), host="127.0.0.1", port=port)
else:
from mcp.server.stdio import stdio_server
async def arun():
async with stdio_server() as streams:
await app.run(streams[0], streams[1], app.create_initialization_options())
anyio.run(arun)
return 0