Spaces:
Running
Running
File size: 10,039 Bytes
ec5b689 |
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 |
#!/usr/bin/env python3
"""
MCP Client Server that connects to Hugging Face Spaces API
This acts as a bridge between Cursor and your Hugging Face Spaces server
"""
import json
import asyncio
import logging
import aiohttp
from typing import Any, Dict, List, Optional
from mcp.server import Server
from mcp.server.models import InitializationOptions
from mcp.server.stdio import stdio_server
from mcp.types import (
Resource,
Tool,
TextContent,
LoggingLevel
)
# Configure logging
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)
# Hugging Face Spaces URL - replace with your actual space URL
HF_SPACE_URL = "https://galcan-mcp-docs-server.hf.space"
# Initialize the MCP server
server = Server("mcp-docs-client")
async def make_request(endpoint: str, method: str = "GET", data: dict = None) -> dict:
"""Make HTTP request to Hugging Face Spaces API"""
url = f"{HF_SPACE_URL}{endpoint}"
try:
async with aiohttp.ClientSession() as session:
if method == "GET":
async with session.get(url) as response:
return await response.json()
elif method == "POST":
async with session.post(url, json=data) as response:
return await response.json()
except Exception as e:
logger.error(f"Request failed: {e}")
return {"error": str(e)}
@server.list_resources()
async def list_resources() -> List[Resource]:
"""List available documentation resources"""
try:
# Get docs from HF Spaces
response = await make_request("/docs")
if "error" in response:
return []
resources = []
for doc in response.get("documents", []):
resources.append(Resource(
uri=f"mcp://docs/{doc.get('id', 'unknown')}",
name=doc.get('title', 'Untitled'),
description=doc.get('content', '')[:200] + "..." if len(doc.get('content', '')) > 200 else doc.get('content', ''),
mimeType="text/plain"
))
return resources
except Exception as e:
logger.error(f"Error listing resources: {e}")
return []
@server.read_resource()
async def read_resource(uri: str) -> str:
"""Read a specific documentation resource"""
try:
# Extract document ID from URI
if uri.startswith("mcp://docs/"):
doc_id = uri.replace("mcp://docs/", "")
# Search for chunks related to this document
search_response = await make_request("/search", "POST", {
"query": doc_id,
"limit": 10
})
if "error" in search_response:
return f"Error: {search_response['error']}"
results = search_response.get("results", [])
if results:
content = "\n\n".join([result.get("text", "") for result in results])
return content
else:
return f"Document {doc_id} not found"
return "Invalid URI"
except Exception as e:
return f"Error reading resource: {e}"
@server.list_tools()
async def list_tools() -> List[Tool]:
"""List available tools"""
return [
Tool(
name="search_docs",
description="Search through MCP documentation chunks on Hugging Face Spaces",
inputSchema={
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "Search query for MCP documentation"
},
"limit": {
"type": "integer",
"description": "Maximum number of results",
"default": 5
}
},
"required": ["query"]
}
),
Tool(
name="get_chunk",
description="Get a specific documentation chunk by ID from Hugging Face Spaces",
inputSchema={
"type": "object",
"properties": {
"chunk_id": {
"type": "string",
"description": "Chunk ID to retrieve"
}
},
"required": ["chunk_id"]
}
),
Tool(
name="list_docs",
description="List all available documents from Hugging Face Spaces",
inputSchema={
"type": "object",
"properties": {}
}
),
Tool(
name="health_check",
description="Check if the Hugging Face Spaces server is running",
inputSchema={
"type": "object",
"properties": {}
}
)
]
@server.call_tool()
async def call_tool(name: str, arguments: Dict[str, Any]) -> List[TextContent]:
"""Handle tool calls by forwarding to Hugging Face Spaces"""
if name == "search_docs":
query = arguments.get("query", "")
limit = arguments.get("limit", 5)
try:
response = await make_request("/search", "POST", {
"query": query,
"limit": limit
})
if "error" in response:
return [TextContent(type="text", text=f"Error: {response['error']}")]
results = response.get("results", [])
total = response.get("total", 0)
if results:
response_text = f"Found {total} results for '{query}':\n\n"
for i, result in enumerate(results, 1):
response_text += f"{i}. **{result.get('title', 'Untitled')}**\n"
response_text += f" {result.get('text', '')[:200]}...\n"
response_text += f" Source: {result.get('filename', 'Unknown')}\n"
if result.get('score'):
response_text += f" Score: {result['score']}\n"
response_text += "\n"
else:
response_text = f"No results found for '{query}'"
return [TextContent(type="text", text=response_text)]
except Exception as e:
return [TextContent(type="text", text=f"Error searching: {e}")]
elif name == "get_chunk":
chunk_id = arguments.get("chunk_id", "")
try:
response = await make_request(f"/chunks/{chunk_id}")
if "error" in response:
return [TextContent(type="text", text=f"Error: {response['error']}")]
if response:
result_text = f"**{response.get('title', 'Untitled')}**\n\n"
result_text += f"{response.get('text', '')}\n\n"
result_text += f"Source: {response.get('filename', 'Unknown')}\n"
result_text += f"URL: {response.get('url', 'N/A')}"
return [TextContent(type="text", text=result_text)]
else:
return [TextContent(type="text", text=f"Chunk {chunk_id} not found")]
except Exception as e:
return [TextContent(type="text", text=f"Error getting chunk: {e}")]
elif name == "list_docs":
try:
response = await make_request("/docs")
if "error" in response:
return [TextContent(type="text", text=f"Error: {response['error']}")]
docs = response.get("documents", [])
if docs:
response_text = "Available documents:\n\n"
for doc in docs:
response_text += f"- **{doc.get('title', 'Untitled')}**\n"
response_text += f" ID: {doc.get('id', 'Unknown')}\n"
response_text += f" URL: {doc.get('url', 'N/A')}\n\n"
else:
response_text = "No documents available"
return [TextContent(type="text", text=response_text)]
except Exception as e:
return [TextContent(type="text", text=f"Error listing docs: {e}")]
elif name == "health_check":
try:
response = await make_request("/")
if "error" in response:
return [TextContent(type="text", text=f"Server error: {response['error']}")]
status = response.get("status", "unknown")
chunks_loaded = response.get("chunks_loaded", 0)
docs_loaded = response.get("docs_loaded", 0)
health_text = f"**Hugging Face Spaces Server Status**\n\n"
health_text += f"Status: {status}\n"
health_text += f"Chunks loaded: {chunks_loaded}\n"
health_text += f"Documents loaded: {docs_loaded}\n"
health_text += f"Server URL: {HF_SPACE_URL}"
return [TextContent(type="text", text=health_text)]
except Exception as e:
return [TextContent(type="text", text=f"Health check failed: {e}")]
else:
return [TextContent(type="text", text=f"Unknown tool: {name}")]
async def main():
"""Main entry point"""
logger.info(f"Starting MCP client server for {HF_SPACE_URL}")
# Run the server
async with stdio_server() as (read_stream, write_stream):
await server.run(
read_stream,
write_stream,
InitializationOptions(
server_name="mcp-docs-client",
server_version="1.0.0",
capabilities=server.get_capabilities(
notification_options=None,
experimental_capabilities=None
)
)
)
if __name__ == "__main__":
asyncio.run(main())
|