Create server.py
Browse files
server.py
ADDED
|
@@ -0,0 +1,64 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import uvicorn
|
| 3 |
+
|
| 4 |
+
from mcp.server.fastmcp import FastMCP
|
| 5 |
+
|
| 6 |
+
from langchain_community.utilities import SQLDatabase
|
| 7 |
+
from langchain_community.tools.sql_database.tool import QuerySQLCheckerTool
|
| 8 |
+
from langchain_openai import ChatOpenAI
|
| 9 |
+
|
| 10 |
+
llm = ChatOpenAI(
|
| 11 |
+
api_key=os.environ.get('OPENAI_API_KEY', None),
|
| 12 |
+
base_url=os.environ['OPENAI_BASE_URL'],
|
| 13 |
+
model='gpt-4o-mini',
|
| 14 |
+
temperature=0
|
| 15 |
+
)
|
| 16 |
+
|
| 17 |
+
# Create an MCP server
|
| 18 |
+
mcp = FastMCP("Credit Card Database Server")
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
credit_card_db = SQLDatabase.from_uri(r"sqlite:///data/ccms.db")
|
| 22 |
+
query_checker_tool = QuerySQLCheckerTool(db=credit_card_db, llm=llm)
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@mcp.tool()
|
| 26 |
+
def sql_db_list_tables():
|
| 27 |
+
"""
|
| 28 |
+
Returns a comma-separated list of table names in the database.
|
| 29 |
+
"""
|
| 30 |
+
return credit_card_db.get_usable_table_names()
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
@mcp.tool()
|
| 34 |
+
def sql_db_schema(table_names: list[str]) -> str:
|
| 35 |
+
"""
|
| 36 |
+
Input 'table_names_str' is a comma-separated string of table names.
|
| 37 |
+
Returns the DDL SQL schema for these tables.
|
| 38 |
+
"""
|
| 39 |
+
return credit_card_db.get_table_info(table_names)
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@mcp.tool()
|
| 43 |
+
def sql_db_query_checker(query: str) -> str:
|
| 44 |
+
"""
|
| 45 |
+
Input 'query' is a SQL query string.
|
| 46 |
+
Checks if the query is valid.
|
| 47 |
+
If the query is valid, it returns the original query.
|
| 48 |
+
If the query is not valid, it returns the corrected query.
|
| 49 |
+
This tool is used to ensure the query is valid before executing it.
|
| 50 |
+
"""
|
| 51 |
+
|
| 52 |
+
return query_checker_tool.run(query)
|
| 53 |
+
|
| 54 |
+
@mcp.tool()
|
| 55 |
+
def sql_db_query(query: str) -> str:
|
| 56 |
+
"""
|
| 57 |
+
Input 'query' is a SQL query string.
|
| 58 |
+
Executes the query (SELECT only) and returns the result.
|
| 59 |
+
"""
|
| 60 |
+
return credit_card_db.run(query)
|
| 61 |
+
|
| 62 |
+
|
| 63 |
+
if __name__ == "__main__":
|
| 64 |
+
uvicorn.run(mcp.streamable_http_app, host="0.0.0.0", port=8000)
|