Update server.py
Browse files
server.py
CHANGED
|
@@ -1,10 +1,115 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
import os
|
| 2 |
import uvicorn
|
| 3 |
import inspect
|
|
|
|
| 4 |
|
| 5 |
from mcp.server.fastmcp import FastMCP
|
| 6 |
from starlette.requests import Request
|
| 7 |
from starlette.responses import PlainTextResponse, JSONResponse
|
|
|
|
| 8 |
|
| 9 |
from langchain_community.utilities import SQLDatabase
|
| 10 |
from langchain_community.tools.sql_database.tool import QuerySQLCheckerTool
|
|
@@ -17,15 +122,36 @@ llm = ChatOpenAI(
|
|
| 17 |
temperature=0
|
| 18 |
)
|
| 19 |
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
# Create an MCP server and the tool registry
|
| 21 |
mcp = FastMCP("Credit Card Database Server")
|
| 22 |
tool_registry = []
|
| 23 |
|
| 24 |
def register_tool(fn):
|
| 25 |
"""Decorator to register tool metadata and with MCP."""
|
| 26 |
-
# Register with MCP
|
| 27 |
mcp.tool()(fn)
|
| 28 |
-
# Save metadata
|
| 29 |
sig = inspect.signature(fn)
|
| 30 |
params = [
|
| 31 |
{
|
|
@@ -98,5 +224,8 @@ async def list_tools(request: Request) -> JSONResponse:
|
|
| 98 |
"""Return all registered tool metadata as JSON."""
|
| 99 |
return JSONResponse(tool_registry)
|
| 100 |
|
|
|
|
|
|
|
|
|
|
| 101 |
if __name__ == "__main__":
|
| 102 |
uvicorn.run(mcp.streamable_http_app, host="0.0.0.0", port=8000)
|
|
|
|
| 1 |
+
# import os
|
| 2 |
+
# import uvicorn
|
| 3 |
+
# import inspect
|
| 4 |
+
|
| 5 |
+
# from mcp.server.fastmcp import FastMCP
|
| 6 |
+
# from starlette.requests import Request
|
| 7 |
+
# from starlette.responses import PlainTextResponse, JSONResponse
|
| 8 |
+
|
| 9 |
+
# from langchain_community.utilities import SQLDatabase
|
| 10 |
+
# from langchain_community.tools.sql_database.tool import QuerySQLCheckerTool
|
| 11 |
+
# from langchain_openai import ChatOpenAI
|
| 12 |
+
|
| 13 |
+
# llm = ChatOpenAI(
|
| 14 |
+
# api_key=os.environ.get('OPENAI_API_KEY', None),
|
| 15 |
+
# base_url=os.environ['OPENAI_BASE_URL'],
|
| 16 |
+
# model='gpt-4o-mini',
|
| 17 |
+
# temperature=0
|
| 18 |
+
# )
|
| 19 |
+
|
| 20 |
+
# # Create an MCP server and the tool registry
|
| 21 |
+
# mcp = FastMCP("Credit Card Database Server")
|
| 22 |
+
# tool_registry = []
|
| 23 |
+
|
| 24 |
+
# def register_tool(fn):
|
| 25 |
+
# """Decorator to register tool metadata and with MCP."""
|
| 26 |
+
# # Register with MCP
|
| 27 |
+
# mcp.tool()(fn)
|
| 28 |
+
# # Save metadata
|
| 29 |
+
# sig = inspect.signature(fn)
|
| 30 |
+
# params = [
|
| 31 |
+
# {
|
| 32 |
+
# "name": param.name,
|
| 33 |
+
# "type": str(param.annotation) if param.annotation is not inspect._empty else "Any",
|
| 34 |
+
# "default": param.default if param.default is not inspect._empty else None,
|
| 35 |
+
# }
|
| 36 |
+
# for param in sig.parameters.values()
|
| 37 |
+
# ]
|
| 38 |
+
# tool_registry.append({
|
| 39 |
+
# "name": fn.__name__,
|
| 40 |
+
# "description": fn.__doc__.strip() if fn.__doc__ else "",
|
| 41 |
+
# "parameters": params,
|
| 42 |
+
# })
|
| 43 |
+
# return fn
|
| 44 |
+
|
| 45 |
+
# credit_card_db = SQLDatabase.from_uri(r"sqlite:///data/ccms.db")
|
| 46 |
+
# query_checker_tool = QuerySQLCheckerTool(db=credit_card_db, llm=llm)
|
| 47 |
+
|
| 48 |
+
# @mcp.custom_route("/", methods=["GET"])
|
| 49 |
+
# async def home(request: Request) -> PlainTextResponse:
|
| 50 |
+
# return PlainTextResponse(
|
| 51 |
+
# """
|
| 52 |
+
# Credit Card Database MCP Server
|
| 53 |
+
# ----
|
| 54 |
+
# Use the following URL to connect with this server
|
| 55 |
+
# https://pgurazada1-credit-card-database-mcp-server.hf.space/mcp/
|
| 56 |
+
|
| 57 |
+
# Access the following URL for a list of tools and their documentation.
|
| 58 |
+
# https://pgurazada1-credit-card-database-mcp-server.hf.space/tools/
|
| 59 |
+
# """
|
| 60 |
+
# )
|
| 61 |
+
|
| 62 |
+
# @register_tool
|
| 63 |
+
# def sql_db_list_tables():
|
| 64 |
+
# """
|
| 65 |
+
# Returns a comma-separated list of table names in the database.
|
| 66 |
+
# """
|
| 67 |
+
# return credit_card_db.get_usable_table_names()
|
| 68 |
+
|
| 69 |
+
# @register_tool
|
| 70 |
+
# def sql_db_schema(table_names: list[str]) -> str:
|
| 71 |
+
# """
|
| 72 |
+
# Input 'table_names_str' is a comma-separated string of table names.
|
| 73 |
+
# Returns the DDL SQL schema for these tables.
|
| 74 |
+
# """
|
| 75 |
+
# return credit_card_db.get_table_info(table_names)
|
| 76 |
+
|
| 77 |
+
# @register_tool
|
| 78 |
+
# def sql_db_query_checker(query: str) -> str:
|
| 79 |
+
# """
|
| 80 |
+
# Input 'query' is a SQL query string.
|
| 81 |
+
# Checks if the query is valid.
|
| 82 |
+
# If the query is valid, it returns the original query.
|
| 83 |
+
# If the query is not valid, it returns the corrected query.
|
| 84 |
+
# This tool is used to ensure the query is valid before executing it.
|
| 85 |
+
# """
|
| 86 |
+
# return query_checker_tool.run(query)
|
| 87 |
+
|
| 88 |
+
# @register_tool
|
| 89 |
+
# def sql_db_query(query: str) -> str:
|
| 90 |
+
# """
|
| 91 |
+
# Input 'query' is a SQL query string.
|
| 92 |
+
# Executes the query (SELECT only) and returns the result.
|
| 93 |
+
# """
|
| 94 |
+
# return credit_card_db.run(query)
|
| 95 |
+
|
| 96 |
+
# @mcp.custom_route("/tools", methods=["GET"])
|
| 97 |
+
# async def list_tools(request: Request) -> JSONResponse:
|
| 98 |
+
# """Return all registered tool metadata as JSON."""
|
| 99 |
+
# return JSONResponse(tool_registry)
|
| 100 |
+
|
| 101 |
+
# if __name__ == "__main__":
|
| 102 |
+
# uvicorn.run(mcp.streamable_http_app, host="0.0.0.0", port=8000)
|
| 103 |
+
|
| 104 |
import os
|
| 105 |
import uvicorn
|
| 106 |
import inspect
|
| 107 |
+
import httpx
|
| 108 |
|
| 109 |
from mcp.server.fastmcp import FastMCP
|
| 110 |
from starlette.requests import Request
|
| 111 |
from starlette.responses import PlainTextResponse, JSONResponse
|
| 112 |
+
from starlette.middleware.base import BaseHTTPMiddleware
|
| 113 |
|
| 114 |
from langchain_community.utilities import SQLDatabase
|
| 115 |
from langchain_community.tools.sql_database.tool import QuerySQLCheckerTool
|
|
|
|
| 122 |
temperature=0
|
| 123 |
)
|
| 124 |
|
| 125 |
+
# Hugging Face Token Auth Middleware
|
| 126 |
+
class HuggingFaceTokenAuthMiddleware(BaseHTTPMiddleware):
|
| 127 |
+
async def dispatch(self, request: Request, call_next):
|
| 128 |
+
# Only protect /mcp/ and /tools endpoints, allow "/" open
|
| 129 |
+
if request.url.path not in ["/", "/mcp/", "/tools"]:
|
| 130 |
+
return await call_next(request)
|
| 131 |
+
# Check Authorization header
|
| 132 |
+
auth = request.headers.get("authorization")
|
| 133 |
+
if not auth or not auth.lower().startswith("bearer "):
|
| 134 |
+
return PlainTextResponse("Missing or invalid Authorization header (expected Bearer token)", status_code=401)
|
| 135 |
+
token = auth.split(" ", 1)[1].strip()
|
| 136 |
+
# Validate token with Hugging Face API
|
| 137 |
+
async with httpx.AsyncClient() as client:
|
| 138 |
+
resp = await client.get(
|
| 139 |
+
"https://huggingface.co/api/whoami-v2",
|
| 140 |
+
headers={"Authorization": f"Bearer {token}"}
|
| 141 |
+
)
|
| 142 |
+
if resp.status_code != 200:
|
| 143 |
+
return PlainTextResponse("Invalid or expired Hugging Face token", status_code=401)
|
| 144 |
+
hf_user_info = resp.json()
|
| 145 |
+
request.state.hf_user = hf_user_info
|
| 146 |
+
return await call_next(request)
|
| 147 |
+
|
| 148 |
# Create an MCP server and the tool registry
|
| 149 |
mcp = FastMCP("Credit Card Database Server")
|
| 150 |
tool_registry = []
|
| 151 |
|
| 152 |
def register_tool(fn):
|
| 153 |
"""Decorator to register tool metadata and with MCP."""
|
|
|
|
| 154 |
mcp.tool()(fn)
|
|
|
|
| 155 |
sig = inspect.signature(fn)
|
| 156 |
params = [
|
| 157 |
{
|
|
|
|
| 224 |
"""Return all registered tool metadata as JSON."""
|
| 225 |
return JSONResponse(tool_registry)
|
| 226 |
|
| 227 |
+
# Add the Hugging Face token auth middleware
|
| 228 |
+
mcp.streamable_http_app.add_middleware(HuggingFaceTokenAuthMiddleware)
|
| 229 |
+
|
| 230 |
if __name__ == "__main__":
|
| 231 |
uvicorn.run(mcp.streamable_http_app, host="0.0.0.0", port=8000)
|