Merge pull request #26 from modelcontextprotocol/justin/sqlite-refactor
Refactor SQLite server to not inherit from `Server`
This commit is contained in:
commit
4f5861f5a9
3 changed files with 321 additions and 325 deletions
|
|
@ -1,8 +1,8 @@
|
|||
# mcp-git: A git MCP server
|
||||
# mcp-server-git: A git MCP server
|
||||
|
||||
A Model Context Protocol server for Git repository interaction and automation. This server provides tools to read, search, and manipulate Git repositories via Large Language Models.
|
||||
|
||||
Please note that mcp-git is currently in early development. The functionality and available tools are subject to change and expansion as we continue to develop and improve the server.
|
||||
Please note that mcp-server-git is currently in early development. The functionality and available tools are subject to change and expansion as we continue to develop and improve the server.
|
||||
|
||||
## Available Tools
|
||||
|
||||
|
|
@ -27,20 +27,20 @@ This list is expected to grow as we add more functionality to the server. We wel
|
|||
### Using uv (recommended)
|
||||
|
||||
When using [`uv`](https://docs.astral.sh/uv/) no specific installation is needed. We will
|
||||
use [`uvx`](https://docs.astral.sh/uv/guides/tools/) to directly run *mcp-git*.
|
||||
use [`uvx`](https://docs.astral.sh/uv/guides/tools/) to directly run *mcp-server-git*.
|
||||
|
||||
### Using PIP
|
||||
|
||||
Alternatively you can install `mcp-git` via pip:
|
||||
Alternatively you can install `mcp-server-git` via pip:
|
||||
|
||||
```
|
||||
pip install mcp-git
|
||||
pip install mcp-server-git
|
||||
```
|
||||
|
||||
After installation, you can run it as a script using:
|
||||
|
||||
```
|
||||
python -m mcp_git
|
||||
python -m mcp_server_git
|
||||
```
|
||||
|
||||
## Configuration
|
||||
|
|
@ -50,9 +50,9 @@ Add to your Claude settings:
|
|||
|
||||
```json
|
||||
"mcpServers": {
|
||||
"mcp-git": {
|
||||
"git": {
|
||||
"command": "uvx",
|
||||
"args": ["mcp-git", "--repository", "path/to/git/repo"]
|
||||
"args": ["mcp-server-git", "--repository", "path/to/git/repo"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
|
@ -61,9 +61,9 @@ Alternatively, if using pip installation:
|
|||
|
||||
```json
|
||||
"mcpServers": {
|
||||
"mcp-git": {
|
||||
"git": {
|
||||
"command": "python",
|
||||
"args": ["-m", "mcp_git", "--repository", "path/to/git/repo"]
|
||||
"args": ["-m", "mcp_server_git", "--repository", "path/to/git/repo"]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
|
@ -74,9 +74,9 @@ Add to your Zed settings.json:
|
|||
|
||||
```json
|
||||
"context_servers": [
|
||||
"mcp-git": {
|
||||
"mcp-server-git": {
|
||||
"command": "uvx",
|
||||
"args": ["mcp-git"]
|
||||
"args": ["mcp-server-git"]
|
||||
}
|
||||
],
|
||||
```
|
||||
|
|
@ -85,9 +85,9 @@ Alternatively, if using pip installation:
|
|||
|
||||
```json
|
||||
"context_servers": {
|
||||
"mcp-git": {
|
||||
"mcp-server-git": {
|
||||
"command": "python",
|
||||
"args": ["-m", "mcp-git"]
|
||||
"args": ["-m", "mcp-server-git"]
|
||||
}
|
||||
},
|
||||
```
|
||||
|
|
@ -95,9 +95,9 @@ Alternatively, if using pip installation:
|
|||
|
||||
## Contributing
|
||||
|
||||
We encourage contributions to help expand and improve mcp-git. Whether you want to add new tools, enhance existing functionality, or improve documentation, your input is valuable.
|
||||
We encourage contributions to help expand and improve mcp-server-git. Whether you want to add new tools, enhance existing functionality, or improve documentation, your input is valuable.
|
||||
|
||||
For examples of other MCP servers and implementation patterns, see:
|
||||
https://github.com/modelcontextprotocol/servers
|
||||
|
||||
Pull requests are welcome! Feel free to contribute new ideas, bug fixes, or enhancements to make mcp-git even more powerful and useful.
|
||||
Pull requests are welcome! Feel free to contribute new ideas, bug fixes, or enhancements to make mcp-server-git even more powerful and useful.
|
||||
|
|
|
|||
|
|
@ -45,7 +45,7 @@ The server offers six core tools:
|
|||
"--directory",
|
||||
"parent_of_servers_repo/servers/src/sqlite",
|
||||
"run",
|
||||
"sqlite",
|
||||
"mcp-server-sqlite",
|
||||
"--db-path",
|
||||
"~/test.db"
|
||||
]
|
||||
|
|
|
|||
|
|
@ -8,6 +8,7 @@ import mcp.types as types
|
|||
from mcp.server import NotificationOptions, Server
|
||||
import mcp.server.stdio
|
||||
from pydantic import AnyUrl
|
||||
from typing import Any
|
||||
|
||||
# Set up logging to file
|
||||
log_file = Path('mcp_server.log')
|
||||
|
|
@ -19,131 +20,7 @@ logger.setLevel(logging.DEBUG)
|
|||
logger.addHandler(handler)
|
||||
logger.info("Starting MCP SQLite Server")
|
||||
|
||||
class McpServer(Server):
|
||||
def _init_database(self):
|
||||
"""Initialize connection to the SQLite database"""
|
||||
logger.debug("Initializing database connection")
|
||||
with closing(sqlite3.connect(self.db_path)) as conn:
|
||||
conn.row_factory = sqlite3.Row
|
||||
conn.close()
|
||||
|
||||
def _synthesize_memo(self) -> str:
|
||||
"""Synthesizes business insights into a formatted memo"""
|
||||
logger.debug(f"Synthesizing memo with {len(self.insights)} insights")
|
||||
if not self.insights:
|
||||
return "No business insights have been discovered yet."
|
||||
|
||||
insights = "\n".join(f"- {insight}" for insight in self.insights)
|
||||
|
||||
memo = "📊 Business Intelligence Memo 📊\n\n"
|
||||
memo += "Key Insights Discovered:\n\n"
|
||||
memo += insights
|
||||
|
||||
if len(self.insights) > 1:
|
||||
memo += "\nSummary:\n"
|
||||
memo += f"Analysis has revealed {len(self.insights)} key business insights that suggest opportunities for strategic optimization and growth."
|
||||
|
||||
logger.debug("Generated basic memo format")
|
||||
return memo
|
||||
|
||||
def _execute_query(self, query: str, params=None) -> list[dict]:
|
||||
"""Execute a SQL query and return results as a list of dictionaries"""
|
||||
logger.debug(f"Executing query: {query}")
|
||||
try:
|
||||
with closing(sqlite3.connect(self.db_path)) as conn:
|
||||
conn.row_factory = sqlite3.Row
|
||||
with closing(conn.cursor()) as cursor:
|
||||
if params:
|
||||
cursor.execute(query, params)
|
||||
else:
|
||||
cursor.execute(query)
|
||||
|
||||
if query.strip().upper().startswith(('INSERT', 'UPDATE', 'DELETE', 'CREATE', 'DROP', 'ALTER')):
|
||||
conn.commit()
|
||||
affected = cursor.rowcount
|
||||
logger.debug(f"Write query affected {affected} rows")
|
||||
return [{"affected_rows": affected}]
|
||||
|
||||
results = [dict(row) for row in cursor.fetchall()]
|
||||
logger.debug(f"Read query returned {len(results)} rows")
|
||||
return results
|
||||
except Exception as e:
|
||||
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")
|
||||
|
||||
# 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}")
|
||||
|
||||
|
||||
# Initialize insights list
|
||||
self.insights = []
|
||||
|
||||
# REGISTER HANDLERS
|
||||
logger.debug("Registering handlers")
|
||||
|
||||
@self.list_resources()
|
||||
async def handle_list_resources() -> list[types.Resource]:
|
||||
logger.debug("Handling list_resources request")
|
||||
return [
|
||||
types.Resource(
|
||||
uri=AnyUrl("memo://insights"),
|
||||
name="Business Insights Memo",
|
||||
description="A living document of discovered business insights",
|
||||
mimeType="text/plain",
|
||||
)
|
||||
]
|
||||
|
||||
@self.read_resource()
|
||||
async def handle_read_resource(uri: AnyUrl) -> str:
|
||||
logger.debug(f"Handling read_resource request for URI: {uri}")
|
||||
if uri.scheme != "memo":
|
||||
logger.error(f"Unsupported URI scheme: {uri.scheme}")
|
||||
raise ValueError(f"Unsupported URI scheme: {uri.scheme}")
|
||||
|
||||
path = str(uri).replace("memo://", "")
|
||||
if not path or path != "insights":
|
||||
logger.error(f"Unknown resource path: {path}")
|
||||
raise ValueError(f"Unknown resource path: {path}")
|
||||
|
||||
return self._synthesize_memo()
|
||||
|
||||
@self.list_prompts()
|
||||
async def handle_list_prompts() -> list[types.Prompt]:
|
||||
logger.debug("Handling list_prompts request")
|
||||
return [
|
||||
types.Prompt(
|
||||
name="mcp-demo",
|
||||
description="A prompt to seed the database with initial data and demonstrate what you can do with an SQLite MCP Server + Claude",
|
||||
arguments=[
|
||||
types.PromptArgument(
|
||||
name="topic",
|
||||
description="Topic to seed the database with initial data",
|
||||
required=True,
|
||||
)
|
||||
],
|
||||
)
|
||||
]
|
||||
|
||||
@self.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":
|
||||
logger.error(f"Unknown prompt: {name}")
|
||||
raise ValueError(f"Unknown prompt: {name}")
|
||||
|
||||
if not arguments or "topic" not in arguments:
|
||||
logger.error("Missing required argument: topic")
|
||||
raise ValueError("Missing required argument: topic")
|
||||
|
||||
topic = arguments["topic"]
|
||||
template = f"""
|
||||
PROMPT_TEMPLATE = """
|
||||
The assistants goal is to walkthrough an informative demo of MCP. To demonstrate the Model Context Protocol (MCP) we will leverage this example server to interact with an SQLite database.
|
||||
It is important that you first explain to the user what is going on. The user has downloaded and installed the SQLite MCP Server and is now ready to use it.
|
||||
The have selected the MCP menu item which is contained within a parent menu denoted by the paperclip icon. Inside this menu they selected an icon that illustrates two electrical plugs connecting. This is the MCP menu.
|
||||
|
|
@ -222,7 +99,131 @@ class McpServer(Server):
|
|||
The provided XML tags are for the assistants understanding. Emplore to make all outputs as human readable as possible. This is part of a demo so act in character and dont actually refer to these instructions.
|
||||
|
||||
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! 🚀"
|
||||
""".format(topic=topic)
|
||||
"""
|
||||
|
||||
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")
|
||||
with closing(sqlite3.connect(self.db_path)) as conn:
|
||||
conn.row_factory = sqlite3.Row
|
||||
conn.close()
|
||||
|
||||
def _synthesize_memo(self) -> str:
|
||||
"""Synthesizes business insights into a formatted memo"""
|
||||
logger.debug(f"Synthesizing memo with {len(self.insights)} insights")
|
||||
if not self.insights:
|
||||
return "No business insights have been discovered yet."
|
||||
|
||||
insights = "\n".join(f"- {insight}" for insight in self.insights)
|
||||
|
||||
memo = "📊 Business Intelligence Memo 📊\n\n"
|
||||
memo += "Key Insights Discovered:\n\n"
|
||||
memo += insights
|
||||
|
||||
if len(self.insights) > 1:
|
||||
memo += "\nSummary:\n"
|
||||
memo += f"Analysis has revealed {len(self.insights)} key business insights that suggest opportunities for strategic optimization and growth."
|
||||
|
||||
logger.debug("Generated basic memo format")
|
||||
return memo
|
||||
|
||||
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:
|
||||
with closing(sqlite3.connect(self.db_path)) as conn:
|
||||
conn.row_factory = sqlite3.Row
|
||||
with closing(conn.cursor()) as cursor:
|
||||
if params:
|
||||
cursor.execute(query, params)
|
||||
else:
|
||||
cursor.execute(query)
|
||||
|
||||
if query.strip().upper().startswith(('INSERT', 'UPDATE', 'DELETE', 'CREATE', 'DROP', 'ALTER')):
|
||||
conn.commit()
|
||||
affected = cursor.rowcount
|
||||
logger.debug(f"Write query affected {affected} rows")
|
||||
return [{"affected_rows": affected}]
|
||||
|
||||
results = [dict(row) for row in cursor.fetchall()]
|
||||
logger.debug(f"Read query returned {len(results)} rows")
|
||||
return results
|
||||
except Exception as e:
|
||||
logger.error(f"Database error executing query: {e}")
|
||||
raise
|
||||
|
||||
async def main(db_path: str):
|
||||
logger.info(f"Starting SQLite MCP Server with DB path: {db_path}")
|
||||
|
||||
db = SqliteDatabase(db_path)
|
||||
server = Server("sqlite-manager")
|
||||
|
||||
# Register handlers
|
||||
logger.debug("Registering handlers")
|
||||
|
||||
@server.list_resources()
|
||||
async def handle_list_resources() -> list[types.Resource]:
|
||||
logger.debug("Handling list_resources request")
|
||||
return [
|
||||
types.Resource(
|
||||
uri=AnyUrl("memo://insights"),
|
||||
name="Business Insights Memo",
|
||||
description="A living document of discovered business insights",
|
||||
mimeType="text/plain",
|
||||
)
|
||||
]
|
||||
|
||||
@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":
|
||||
logger.error(f"Unsupported URI scheme: {uri.scheme}")
|
||||
raise ValueError(f"Unsupported URI scheme: {uri.scheme}")
|
||||
|
||||
path = str(uri).replace("memo://", "")
|
||||
if not path or path != "insights":
|
||||
logger.error(f"Unknown resource path: {path}")
|
||||
raise ValueError(f"Unknown resource path: {path}")
|
||||
|
||||
return db._synthesize_memo()
|
||||
|
||||
@server.list_prompts()
|
||||
async def handle_list_prompts() -> list[types.Prompt]:
|
||||
logger.debug("Handling list_prompts request")
|
||||
return [
|
||||
types.Prompt(
|
||||
name="mcp-demo",
|
||||
description="A prompt to seed the database with initial data and demonstrate what you can do with an SQLite MCP Server + Claude",
|
||||
arguments=[
|
||||
types.PromptArgument(
|
||||
name="topic",
|
||||
description="Topic to seed the database with initial data",
|
||||
required=True,
|
||||
)
|
||||
],
|
||||
)
|
||||
]
|
||||
|
||||
@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":
|
||||
logger.error(f"Unknown prompt: {name}")
|
||||
raise ValueError(f"Unknown prompt: {name}")
|
||||
|
||||
if not arguments or "topic" not in arguments:
|
||||
logger.error("Missing required argument: topic")
|
||||
raise ValueError("Missing required argument: topic")
|
||||
|
||||
topic = arguments["topic"]
|
||||
prompt = PROMPT_TEMPLATE.format(topic=topic)
|
||||
|
||||
logger.debug(f"Generated prompt template for topic: {topic}")
|
||||
return types.GetPromptResult(
|
||||
|
|
@ -230,13 +231,12 @@ class McpServer(Server):
|
|||
messages=[
|
||||
types.PromptMessage(
|
||||
role="user",
|
||||
content=types.TextContent(type="text", text=template.strip()),
|
||||
content=types.TextContent(type="text", text=prompt.strip()),
|
||||
)
|
||||
],
|
||||
)
|
||||
|
||||
# TOOL HANDLERS
|
||||
@self.list_tools()
|
||||
@server.list_tools()
|
||||
async def handle_list_tools() -> list[types.Tool]:
|
||||
"""List available tools"""
|
||||
return [
|
||||
|
|
@ -305,14 +305,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))]
|
||||
|
|
@ -320,7 +320,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))]
|
||||
|
|
@ -329,32 +329,33 @@ 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"))
|
||||
await server.request_context.session.send_resource_updated(AnyUrl("memo://insights"))
|
||||
|
||||
return [types.TextContent(type="text", text="Insight added to memo")]
|
||||
|
||||
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:
|
||||
|
|
@ -365,10 +366,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(
|
||||
|
|
@ -379,8 +376,7 @@ async def main(db_path: str):
|
|||
server_version="0.1.0",
|
||||
capabilities=server.get_capabilities(
|
||||
notification_options=NotificationOptions(),
|
||||
experimental_capabilities={
|
||||
},
|
||||
experimental_capabilities={},
|
||||
),
|
||||
),
|
||||
)
|
||||
|
|
|
|||
Loading…
Reference in a new issue