Refactor to not inherit from Server
This commit is contained in:
parent
812e8213dc
commit
a184344b85
1 changed files with 191 additions and 196 deletions
|
|
@ -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! 🚀"
|
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):
|
def _init_database(self):
|
||||||
"""Initialize connection to the SQLite database"""
|
"""Initialize connection to the SQLite database"""
|
||||||
logger.debug("Initializing database connection")
|
logger.debug("Initializing database connection")
|
||||||
|
|
@ -127,7 +133,7 @@ class McpServer(Server):
|
||||||
logger.debug("Generated basic memo format")
|
logger.debug("Generated basic memo format")
|
||||||
return memo
|
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"""
|
"""Execute a SQL query and return results as a list of dictionaries"""
|
||||||
logger.debug(f"Executing query: {query}")
|
logger.debug(f"Executing query: {query}")
|
||||||
try:
|
try:
|
||||||
|
|
@ -152,24 +158,16 @@ class McpServer(Server):
|
||||||
logger.error(f"Database error executing query: {e}")
|
logger.error(f"Database error executing query: {e}")
|
||||||
raise
|
raise
|
||||||
|
|
||||||
def __init__(self, db_path: str = "~/sqlite_mcp_server.db"):
|
async def main(db_path: str):
|
||||||
logger.info("Initializing McpServer")
|
logger.info(f"Starting SQLite MCP Server with DB path: {db_path}")
|
||||||
super().__init__("sqlite-manager")
|
|
||||||
|
|
||||||
# Initialize SQLite database
|
db = SqliteDatabase(db_path)
|
||||||
self.db_path = str(Path(db_path).expanduser())
|
server = Server("sqlite-manager")
|
||||||
Path(self.db_path).parent.mkdir(parents=True, exist_ok=True)
|
|
||||||
self._init_database()
|
|
||||||
logger.debug(f"Initialized database at {self.db_path}")
|
|
||||||
|
|
||||||
|
# Register handlers
|
||||||
# Initialize insights list
|
|
||||||
self.insights = []
|
|
||||||
|
|
||||||
# REGISTER HANDLERS
|
|
||||||
logger.debug("Registering handlers")
|
logger.debug("Registering handlers")
|
||||||
|
|
||||||
@self.list_resources()
|
@server.list_resources()
|
||||||
async def handle_list_resources() -> list[types.Resource]:
|
async def handle_list_resources() -> list[types.Resource]:
|
||||||
logger.debug("Handling list_resources request")
|
logger.debug("Handling list_resources request")
|
||||||
return [
|
return [
|
||||||
|
|
@ -181,7 +179,7 @@ class McpServer(Server):
|
||||||
)
|
)
|
||||||
]
|
]
|
||||||
|
|
||||||
@self.read_resource()
|
@server.read_resource()
|
||||||
async def handle_read_resource(uri: AnyUrl) -> str:
|
async def handle_read_resource(uri: AnyUrl) -> str:
|
||||||
logger.debug(f"Handling read_resource request for URI: {uri}")
|
logger.debug(f"Handling read_resource request for URI: {uri}")
|
||||||
if uri.scheme != "memo":
|
if uri.scheme != "memo":
|
||||||
|
|
@ -193,9 +191,9 @@ class McpServer(Server):
|
||||||
logger.error(f"Unknown resource path: {path}")
|
logger.error(f"Unknown resource path: {path}")
|
||||||
raise ValueError(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]:
|
async def handle_list_prompts() -> list[types.Prompt]:
|
||||||
logger.debug("Handling list_prompts request")
|
logger.debug("Handling list_prompts request")
|
||||||
return [
|
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:
|
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}")
|
logger.debug(f"Handling get_prompt request for {name} with args {arguments}")
|
||||||
if name != "mcp-demo":
|
if name != "mcp-demo":
|
||||||
|
|
@ -237,8 +235,7 @@ class McpServer(Server):
|
||||||
],
|
],
|
||||||
)
|
)
|
||||||
|
|
||||||
# TOOL HANDLERS
|
@server.list_tools()
|
||||||
@self.list_tools()
|
|
||||||
async def handle_list_tools() -> list[types.Tool]:
|
async def handle_list_tools() -> list[types.Tool]:
|
||||||
"""List available tools"""
|
"""List available tools"""
|
||||||
return [
|
return [
|
||||||
|
|
@ -307,14 +304,14 @@ class McpServer(Server):
|
||||||
),
|
),
|
||||||
]
|
]
|
||||||
|
|
||||||
@self.call_tool()
|
@server.call_tool()
|
||||||
async def handle_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]:
|
) -> list[types.TextContent | types.ImageContent | types.EmbeddedResource]:
|
||||||
"""Handle tool execution requests"""
|
"""Handle tool execution requests"""
|
||||||
try:
|
try:
|
||||||
if name == "list-tables":
|
if name == "list-tables":
|
||||||
results = self._execute_query(
|
results = db._execute_query(
|
||||||
"SELECT name FROM sqlite_master WHERE type='table'"
|
"SELECT name FROM sqlite_master WHERE type='table'"
|
||||||
)
|
)
|
||||||
return [types.TextContent(type="text", text=str(results))]
|
return [types.TextContent(type="text", text=str(results))]
|
||||||
|
|
@ -322,7 +319,7 @@ class McpServer(Server):
|
||||||
elif name == "describe-table":
|
elif name == "describe-table":
|
||||||
if not arguments or "table_name" not in arguments:
|
if not arguments or "table_name" not in arguments:
|
||||||
raise ValueError("Missing table_name argument")
|
raise ValueError("Missing table_name argument")
|
||||||
results = self._execute_query(
|
results = db._execute_query(
|
||||||
f"PRAGMA table_info({arguments['table_name']})"
|
f"PRAGMA table_info({arguments['table_name']})"
|
||||||
)
|
)
|
||||||
return [types.TextContent(type="text", text=str(results))]
|
return [types.TextContent(type="text", text=str(results))]
|
||||||
|
|
@ -331,8 +328,8 @@ class McpServer(Server):
|
||||||
if not arguments or "insight" not in arguments:
|
if not arguments or "insight" not in arguments:
|
||||||
raise ValueError("Missing insight argument")
|
raise ValueError("Missing insight argument")
|
||||||
|
|
||||||
self.insights.append(arguments["insight"])
|
db.insights.append(arguments["insight"])
|
||||||
memo = self._synthesize_memo()
|
_ = db._synthesize_memo()
|
||||||
|
|
||||||
# Notify clients that the memo resource has changed
|
# Notify clients that the memo resource has changed
|
||||||
await self.request_context.session.send_resource_updated(AnyUrl("memo://insights"))
|
await self.request_context.session.send_resource_updated(AnyUrl("memo://insights"))
|
||||||
|
|
@ -341,22 +338,25 @@ class McpServer(Server):
|
||||||
if not arguments:
|
if not arguments:
|
||||||
raise ValueError("Missing arguments")
|
raise ValueError("Missing arguments")
|
||||||
|
|
||||||
|
if not arguments:
|
||||||
|
raise ValueError("Missing arguments")
|
||||||
|
|
||||||
if name == "read-query":
|
if name == "read-query":
|
||||||
if not arguments["query"].strip().upper().startswith("SELECT"):
|
if not arguments["query"].strip().upper().startswith("SELECT"):
|
||||||
raise ValueError("Only SELECT queries are allowed for read-query")
|
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))]
|
return [types.TextContent(type="text", text=str(results))]
|
||||||
|
|
||||||
elif name == "write-query":
|
elif name == "write-query":
|
||||||
if arguments["query"].strip().upper().startswith("SELECT"):
|
if arguments["query"].strip().upper().startswith("SELECT"):
|
||||||
raise ValueError("SELECT queries are not allowed for write-query")
|
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))]
|
return [types.TextContent(type="text", text=str(results))]
|
||||||
|
|
||||||
elif name == "create-table":
|
elif name == "create-table":
|
||||||
if not arguments["query"].strip().upper().startswith("CREATE TABLE"):
|
if not arguments["query"].strip().upper().startswith("CREATE TABLE"):
|
||||||
raise ValueError("Only CREATE TABLE statements are allowed")
|
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")]
|
return [types.TextContent(type="text", text="Table created successfully")]
|
||||||
|
|
||||||
else:
|
else:
|
||||||
|
|
@ -367,10 +367,6 @@ class McpServer(Server):
|
||||||
except Exception as e:
|
except Exception as e:
|
||||||
return [types.TextContent(type="text", text=f"Error: {str(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):
|
async with mcp.server.stdio.stdio_server() as (read_stream, write_stream):
|
||||||
logger.info("Server running with stdio transport")
|
logger.info("Server running with stdio transport")
|
||||||
await server.run(
|
await server.run(
|
||||||
|
|
@ -381,8 +377,7 @@ async def main(db_path: str):
|
||||||
server_version="0.1.0",
|
server_version="0.1.0",
|
||||||
capabilities=server.get_capabilities(
|
capabilities=server.get_capabilities(
|
||||||
notification_options=NotificationOptions(),
|
notification_options=NotificationOptions(),
|
||||||
experimental_capabilities={
|
experimental_capabilities={},
|
||||||
},
|
|
||||||
),
|
),
|
||||||
),
|
),
|
||||||
)
|
)
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue