Refactor to not inherit from Server

This commit is contained in:
Justin Spahr-Summers 2024-11-21 21:38:06 +00:00
commit a184344b85
No known key found for this signature in database

View file

@ -100,7 +100,13 @@ The provided XML tags are for the assistants understanding. Emplore to make all
Start your first message fully in character with something like "Oh, Hey there! I see you've chosen the topic {topic}. Let's get started! 🚀"
"""
class McpServer(Server):
class SqliteDatabase:
def __init__(self, db_path: str):
self.db_path = str(Path(db_path).expanduser())
Path(self.db_path).parent.mkdir(parents=True, exist_ok=True)
self._init_database()
self.insights: list[str] = []
def _init_database(self):
"""Initialize connection to the SQLite database"""
logger.debug("Initializing database connection")
@ -127,7 +133,7 @@ class McpServer(Server):
logger.debug("Generated basic memo format")
return memo
def _execute_query(self, query: str, params=None) -> list[dict]:
def _execute_query(self, query: str, params: dict[str, Any] | None = None) -> list[dict[str, Any]]:
"""Execute a SQL query and return results as a list of dictionaries"""
logger.debug(f"Executing query: {query}")
try:
@ -152,24 +158,16 @@ class McpServer(Server):
logger.error(f"Database error executing query: {e}")
raise
def __init__(self, db_path: str = "~/sqlite_mcp_server.db"):
logger.info("Initializing McpServer")
super().__init__("sqlite-manager")
async def main(db_path: str):
logger.info(f"Starting SQLite MCP Server with DB path: {db_path}")
# Initialize SQLite database
self.db_path = str(Path(db_path).expanduser())
Path(self.db_path).parent.mkdir(parents=True, exist_ok=True)
self._init_database()
logger.debug(f"Initialized database at {self.db_path}")
db = SqliteDatabase(db_path)
server = Server("sqlite-manager")
# Initialize insights list
self.insights = []
# REGISTER HANDLERS
# Register handlers
logger.debug("Registering handlers")
@self.list_resources()
@server.list_resources()
async def handle_list_resources() -> list[types.Resource]:
logger.debug("Handling list_resources request")
return [
@ -181,7 +179,7 @@ class McpServer(Server):
)
]
@self.read_resource()
@server.read_resource()
async def handle_read_resource(uri: AnyUrl) -> str:
logger.debug(f"Handling read_resource request for URI: {uri}")
if uri.scheme != "memo":
@ -193,9 +191,9 @@ class McpServer(Server):
logger.error(f"Unknown resource path: {path}")
raise ValueError(f"Unknown resource path: {path}")
return self._synthesize_memo()
return db._synthesize_memo()
@self.list_prompts()
@server.list_prompts()
async def handle_list_prompts() -> list[types.Prompt]:
logger.debug("Handling list_prompts request")
return [
@ -212,7 +210,7 @@ class McpServer(Server):
)
]
@self.get_prompt()
@server.get_prompt()
async def handle_get_prompt(name: str, arguments: dict[str, str] | None) -> types.GetPromptResult:
logger.debug(f"Handling get_prompt request for {name} with args {arguments}")
if name != "mcp-demo":
@ -237,8 +235,7 @@ class McpServer(Server):
],
)
# TOOL HANDLERS
@self.list_tools()
@server.list_tools()
async def handle_list_tools() -> list[types.Tool]:
"""List available tools"""
return [
@ -307,14 +304,14 @@ class McpServer(Server):
),
]
@self.call_tool()
@server.call_tool()
async def handle_call_tool(
name: str, arguments: dict | None
name: str, arguments: dict[str, Any] | None
) -> list[types.TextContent | types.ImageContent | types.EmbeddedResource]:
"""Handle tool execution requests"""
try:
if name == "list-tables":
results = self._execute_query(
results = db._execute_query(
"SELECT name FROM sqlite_master WHERE type='table'"
)
return [types.TextContent(type="text", text=str(results))]
@ -322,7 +319,7 @@ class McpServer(Server):
elif name == "describe-table":
if not arguments or "table_name" not in arguments:
raise ValueError("Missing table_name argument")
results = self._execute_query(
results = db._execute_query(
f"PRAGMA table_info({arguments['table_name']})"
)
return [types.TextContent(type="text", text=str(results))]
@ -331,8 +328,8 @@ class McpServer(Server):
if not arguments or "insight" not in arguments:
raise ValueError("Missing insight argument")
self.insights.append(arguments["insight"])
memo = self._synthesize_memo()
db.insights.append(arguments["insight"])
_ = db._synthesize_memo()
# Notify clients that the memo resource has changed
await self.request_context.session.send_resource_updated(AnyUrl("memo://insights"))
@ -341,22 +338,25 @@ class McpServer(Server):
if not arguments:
raise ValueError("Missing arguments")
if not arguments:
raise ValueError("Missing arguments")
if name == "read-query":
if not arguments["query"].strip().upper().startswith("SELECT"):
raise ValueError("Only SELECT queries are allowed for read-query")
results = self._execute_query(arguments["query"])
results = db._execute_query(arguments["query"])
return [types.TextContent(type="text", text=str(results))]
elif name == "write-query":
if arguments["query"].strip().upper().startswith("SELECT"):
raise ValueError("SELECT queries are not allowed for write-query")
results = self._execute_query(arguments["query"])
results = db._execute_query(arguments["query"])
return [types.TextContent(type="text", text=str(results))]
elif name == "create-table":
if not arguments["query"].strip().upper().startswith("CREATE TABLE"):
raise ValueError("Only CREATE TABLE statements are allowed")
self._execute_query(arguments["query"])
db._execute_query(arguments["query"])
return [types.TextContent(type="text", text="Table created successfully")]
else:
@ -367,10 +367,6 @@ class McpServer(Server):
except Exception as e:
return [types.TextContent(type="text", text=f"Error: {str(e)}")]
async def main(db_path: str):
logger.info(f"Starting SQLite MCP Server with DB path: {db_path}")
server = McpServer(db_path)
async with mcp.server.stdio.stdio_server() as (read_stream, write_stream):
logger.info("Server running with stdio transport")
await server.run(
@ -381,8 +377,7 @@ async def main(db_path: str):
server_version="0.1.0",
capabilities=server.get_capabilities(
notification_options=NotificationOptions(),
experimental_capabilities={
},
experimental_capabilities={},
),
),
)