From 812e8213dc87c2a146288bc1508d83c24abd5385 Mon Sep 17 00:00:00 2001 From: Justin Spahr-Summers Date: Thu, 21 Nov 2024 21:36:16 +0000 Subject: [PATCH 1/5] Extract prompt template from inline --- src/sqlite/src/mcp_server_sqlite/server.py | 202 +++++++++++---------- 1 file changed, 102 insertions(+), 100 deletions(-) diff --git a/src/sqlite/src/mcp_server_sqlite/server.py b/src/sqlite/src/mcp_server_sqlite/server.py index 14db5674..48ba0a9b 100644 --- a/src/sqlite/src/mcp_server_sqlite/server.py +++ b/src/sqlite/src/mcp_server_sqlite/server.py @@ -19,6 +19,87 @@ logger.addHandler(handler) logger.info("Starting MCP SQLite Server") +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. +Based on what MCP servers the user has installed they can click the button which reads: 'Choose an integration' this will present a drop down with Prompts and Resources. The user hase selected the prompt titled: 'mcp-demo'. +This text file is that prompt. The goal of the following instructions is to walk the user through the process of using the 3 core aspects of an MCP server. These are: Prompts, Tools, and Resources. +They have already used a prompt and provided a topic. The topic is: {topic}. The user is now ready to begin the demo. +Here is some more information about mcp and this specific mcp server: + +Prompts: +This server provides a pre-written prompt called "mcp-demo" that helps users create and analyze database scenarios. The prompt accepts a "topic" argument and guides users through creating tables, analyzing data, and generating insights. For example, if a user provides "retail sales" as the topic, the prompt will help create relevant database tables and guide the analysis process. Prompts basically serve as interactive templates that help structure the conversation with the LLM in a useful way. +Resources: +This server exposes one key resource: "memo://insights", which is a business insights memo that gets automatically updated throughout the analysis process. As users analyze the database and discover insights, the memo resource gets updated in real-time to reflect new findings. The memo can even be enhanced with Claude's help if an Anthropic API key is provided, turning raw insights into a well-structured business document. Resources act as living documents that provide context to the conversation. +Tools: +This server provides several SQL-related tools: +"read-query": Executes SELECT queries to read data from the database +"write-query": Executes INSERT, UPDATE, or DELETE queries to modify data +"create-table": Creates new tables in the database +"list-tables": Shows all existing tables +"describe-table": Shows the schema for a specific table +"append-insight": Adds a new business insight to the memo resource + + +You are an AI assistant tasked with generating a comprehensive business scenario based on a given topic. +Your goal is to create a narrative that involves a data-driven business problem, develop a database structure to support it, generate relevant queries, create a dashboard, and provide a final solution. + +At each step you will pause for user input to guide the scenario creation process. Overall ensure the scenario is engaging, informative, and demonstrates the capabilities of the SQLite MCP Server. +You should guide the scenario to completion. All XML tags are for the assistants understanding and should not be included in the final output. + +1. The user has chosen the topic: {topic}. + +2. Create a business problem narrative: +a. Describe a high-level business situation or problem based on the given topic. +b. Include a protagonist (the user) who needs to collect and analyze data from a database. +c. Add an external, potentially comedic reason why the data hasn't been prepared yet. +d. Mention an approaching deadline and the need to use Claude (you) as a business tool to help. + +3. Setup the data: +a. Instead of asking about the data that is required for the scenario, just go ahead and use the tools to create the data. Inform the user you are "Setting up the data". +b. Design a set of table schemas that represent the data needed for the business problem. +c. Include at least 2-3 tables with appropriate columns and data types. +d. Leverage the tools to create the tables in the SQLite database. +e. Create INSERT statements to populate each table with relevant synthetic data. +f. Ensure the data is diverse and representative of the business problem. +g. Include at least 10-15 rows of data for each table. + +4. Pause for user input: +a. Summarize to the user what data we have created. +b. Present the user with a set of multiple choices for the next steps. +c. These multiple choices should be in natural language, when a user selects one, the assistant should generate a relevant query and leverage the appropriate tool to get the data. + +6. Iterate on queries: +a. Present 1 additional multiple-choice query options to the user. Its importnat to not loop too many times as this is a short demo. +b. Explain the purpose of each query option. +c. Wait for the user to select one of the query options. +d. After each query be sure to opine on the results. +e. Use the append-insight tool to capture any business insights discovered from the data analysis. + +7. Generate a dashboard: +a. Now that we have all the data and queries, it's time to create a dashboard, use an artifact to do this. +b. Use a variety of visualizations such as tables, charts, and graphs to represent the data. +c. Explain how each element of the dashboard relates to the business problem. +d. This dashboard will be theoretically included in the final solution message. + +8. Craft the final solution message: +a. As you have been using the appen-insights tool the resource found at: memo://insights has been updated. +b. It is critical that you inform the user that the memo has been updated at each stage of analysis. +c. Ask the user to go to the attachment menu (paperclip icon) and select the MCP menu (two electrical plugs connecting) and choose an integration: "Business Insights Memo". +d. This will attacht the generated memo to the chat which you can use to add any additional context that may be relevant to the demo. +e. Present the final memo to the user in an artifact. + +9. Wrap up the scenario: +a. Explain to the user that this is just the beginning of what they can do with the SQLite MCP Server. + + +Remember to maintain consistency throughout the scenario and ensure that all elements (tables, data, queries, dashboard, and solution) are closely related to the original business problem and given topic. +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! 🚀" +""" + class McpServer(Server): def _init_database(self): """Initialize connection to the SQLite database""" @@ -26,23 +107,23 @@ def _init_database(self): 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 @@ -57,13 +138,13 @@ def _execute_query(self, query: str, params=None) -> list[dict]: 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 @@ -74,26 +155,26 @@ def _execute_query(self, query: str, params=None) -> list[dict]: 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"), + uri=AnyUrl("memo://insights"), name="Business Insights Memo", description="A living document of discovered business insights", mimeType="text/plain", @@ -106,12 +187,12 @@ async def handle_read_resource(uri: AnyUrl) -> str: 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://", "") + + 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() @@ -143,86 +224,7 @@ async def handle_get_prompt(name: str, arguments: dict[str, str] | None) -> type raise ValueError("Missing required argument: topic") topic = arguments["topic"] - template = f""" - 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. - Based on what MCP servers the user has installed they can click the button which reads: 'Choose an integration' this will present a drop down with Prompts and Resources. The user hase selected the prompt titled: 'mcp-demo'. - This text file is that prompt. The goal of the following instructions is to walk the user through the process of using the 3 core aspects of an MCP server. These are: Prompts, Tools, and Resources. - They have already used a prompt and provided a topic. The topic is: {topic}. The user is now ready to begin the demo. - Here is some more information about mcp and this specific mcp server: - - Prompts: - This server provides a pre-written prompt called "mcp-demo" that helps users create and analyze database scenarios. The prompt accepts a "topic" argument and guides users through creating tables, analyzing data, and generating insights. For example, if a user provides "retail sales" as the topic, the prompt will help create relevant database tables and guide the analysis process. Prompts basically serve as interactive templates that help structure the conversation with the LLM in a useful way. - Resources: - This server exposes one key resource: "memo://insights", which is a business insights memo that gets automatically updated throughout the analysis process. As users analyze the database and discover insights, the memo resource gets updated in real-time to reflect new findings. The memo can even be enhanced with Claude's help if an Anthropic API key is provided, turning raw insights into a well-structured business document. Resources act as living documents that provide context to the conversation. - Tools: - This server provides several SQL-related tools: - "read-query": Executes SELECT queries to read data from the database - "write-query": Executes INSERT, UPDATE, or DELETE queries to modify data - "create-table": Creates new tables in the database - "list-tables": Shows all existing tables - "describe-table": Shows the schema for a specific table - "append-insight": Adds a new business insight to the memo resource - - - You are an AI assistant tasked with generating a comprehensive business scenario based on a given topic. - Your goal is to create a narrative that involves a data-driven business problem, develop a database structure to support it, generate relevant queries, create a dashboard, and provide a final solution. - - At each step you will pause for user input to guide the scenario creation process. Overall ensure the scenario is engaging, informative, and demonstrates the capabilities of the SQLite MCP Server. - You should guide the scenario to completion. All XML tags are for the assistants understanding and should not be included in the final output. - - 1. The user has chosen the topic: {topic}. - - 2. Create a business problem narrative: - a. Describe a high-level business situation or problem based on the given topic. - b. Include a protagonist (the user) who needs to collect and analyze data from a database. - c. Add an external, potentially comedic reason why the data hasn't been prepared yet. - d. Mention an approaching deadline and the need to use Claude (you) as a business tool to help. - - 3. Setup the data: - a. Instead of asking about the data that is required for the scenario, just go ahead and use the tools to create the data. Inform the user you are "Setting up the data". - b. Design a set of table schemas that represent the data needed for the business problem. - c. Include at least 2-3 tables with appropriate columns and data types. - d. Leverage the tools to create the tables in the SQLite database. - e. Create INSERT statements to populate each table with relevant synthetic data. - f. Ensure the data is diverse and representative of the business problem. - g. Include at least 10-15 rows of data for each table. - - 4. Pause for user input: - a. Summarize to the user what data we have created. - b. Present the user with a set of multiple choices for the next steps. - c. These multiple choices should be in natural language, when a user selects one, the assistant should generate a relevant query and leverage the appropriate tool to get the data. - - 6. Iterate on queries: - a. Present 1 additional multiple-choice query options to the user. Its importnat to not loop too many times as this is a short demo. - b. Explain the purpose of each query option. - c. Wait for the user to select one of the query options. - d. After each query be sure to opine on the results. - e. Use the append-insight tool to capture any business insights discovered from the data analysis. - - 7. Generate a dashboard: - a. Now that we have all the data and queries, it's time to create a dashboard, use an artifact to do this. - b. Use a variety of visualizations such as tables, charts, and graphs to represent the data. - c. Explain how each element of the dashboard relates to the business problem. - d. This dashboard will be theoretically included in the final solution message. - - 8. Craft the final solution message: - a. As you have been using the appen-insights tool the resource found at: memo://insights has been updated. - b. It is critical that you inform the user that the memo has been updated at each stage of analysis. - c. Ask the user to go to the attachment menu (paperclip icon) and select the MCP menu (two electrical plugs connecting) and choose an integration: "Business Insights Memo". - d. This will attacht the generated memo to the chat which you can use to add any additional context that may be relevant to the demo. - e. Present the final memo to the user in an artifact. - - 9. Wrap up the scenario: - a. Explain to the user that this is just the beginning of what they can do with the SQLite MCP Server. - - - Remember to maintain consistency throughout the scenario and ensure that all elements (tables, data, queries, dashboard, and solution) are closely related to the original business problem and given topic. - 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) + prompt = PROMPT_TEMPLATE.format(topic=topic) logger.debug(f"Generated prompt template for topic: {topic}") return types.GetPromptResult( @@ -230,7 +232,7 @@ async def handle_get_prompt(name: str, arguments: dict[str, str] | None) -> type messages=[ types.PromptMessage( role="user", - content=types.TextContent(type="text", text=template.strip()), + content=types.TextContent(type="text", text=prompt.strip()), ) ], ) @@ -316,7 +318,7 @@ async def handle_call_tool( "SELECT name FROM sqlite_master WHERE type='table'" ) return [types.TextContent(type="text", text=str(results))] - + elif name == "describe-table": if not arguments or "table_name" not in arguments: raise ValueError("Missing table_name argument") @@ -328,10 +330,10 @@ async def handle_call_tool( elif name == "append-insight": if not arguments or "insight" not in arguments: raise ValueError("Missing insight argument") - + self.insights.append(arguments["insight"]) memo = self._synthesize_memo() - + # Notify clients that the memo resource has changed await self.request_context.session.send_resource_updated(AnyUrl("memo://insights")) @@ -368,7 +370,7 @@ async def handle_call_tool( 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( From a184344b852a013e91e2043f06d404e668b81b23 Mon Sep 17 00:00:00 2001 From: Justin Spahr-Summers Date: Thu, 21 Nov 2024 21:38:06 +0000 Subject: [PATCH 2/5] Refactor to not inherit from `Server` --- src/sqlite/src/mcp_server_sqlite/server.py | 387 ++++++++++----------- 1 file changed, 191 insertions(+), 196 deletions(-) diff --git a/src/sqlite/src/mcp_server_sqlite/server.py b/src/sqlite/src/mcp_server_sqlite/server.py index 48ba0a9b..5ca3b8fa 100644 --- a/src/sqlite/src/mcp_server_sqlite/server.py +++ b/src/sqlite/src/mcp_server_sqlite/server.py @@ -100,7 +100,13 @@ 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 @@ def _synthesize_memo(self) -> str: 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,187 +158,178 @@ def _execute_query(self, query: str, params=None) -> list[dict]: 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") +async def main(db_path: str): + logger.info(f"Starting SQLite MCP Server with DB path: {db_path}") - @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"] - prompt = PROMPT_TEMPLATE.format(topic=topic) - - logger.debug(f"Generated prompt template for topic: {topic}") - return types.GetPromptResult( - description=f"Demo template for {topic}", - messages=[ - types.PromptMessage( - role="user", - content=types.TextContent(type="text", text=prompt.strip()), + 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( + description=f"Demo template for {topic}", + messages=[ + types.PromptMessage( + role="user", + content=types.TextContent(type="text", text=prompt.strip()), + ) + ], + ) - # TOOL HANDLERS - @self.list_tools() - async def handle_list_tools() -> list[types.Tool]: - """List available tools""" - return [ - types.Tool( - name="read-query", - description="Execute a SELECT query on the SQLite database", - inputSchema={ - "type": "object", - "properties": { - "query": {"type": "string", "description": "SELECT SQL query to execute"}, - }, - "required": ["query"], + @server.list_tools() + async def handle_list_tools() -> list[types.Tool]: + """List available tools""" + return [ + types.Tool( + name="read-query", + description="Execute a SELECT query on the SQLite database", + inputSchema={ + "type": "object", + "properties": { + "query": {"type": "string", "description": "SELECT SQL query to execute"}, }, - ), - types.Tool( - name="write-query", - description="Execute an INSERT, UPDATE, or DELETE query on the SQLite database", - inputSchema={ - "type": "object", - "properties": { - "query": {"type": "string", "description": "SQL query to execute"}, - }, - "required": ["query"], - }, - ), - types.Tool( - name="create-table", - description="Create a new table in the SQLite database", - inputSchema={ - "type": "object", - "properties": { - "query": {"type": "string", "description": "CREATE TABLE SQL statement"}, - }, - "required": ["query"], + "required": ["query"], + }, + ), + types.Tool( + name="write-query", + description="Execute an INSERT, UPDATE, or DELETE query on the SQLite database", + inputSchema={ + "type": "object", + "properties": { + "query": {"type": "string", "description": "SQL query to execute"}, }, - ), - types.Tool( - name="list-tables", - description="List all tables in the SQLite database", - inputSchema={ - "type": "object", - "properties": {}, + "required": ["query"], + }, + ), + types.Tool( + name="create-table", + description="Create a new table in the SQLite database", + inputSchema={ + "type": "object", + "properties": { + "query": {"type": "string", "description": "CREATE TABLE SQL statement"}, }, - ), - types.Tool( - name="describe-table", - description="Get the schema information for a specific table", - inputSchema={ - "type": "object", - "properties": { - "table_name": {"type": "string", "description": "Name of the table to describe"}, - }, - "required": ["table_name"], + "required": ["query"], + }, + ), + types.Tool( + name="list-tables", + description="List all tables in the SQLite database", + inputSchema={ + "type": "object", + "properties": {}, + }, + ), + types.Tool( + name="describe-table", + description="Get the schema information for a specific table", + inputSchema={ + "type": "object", + "properties": { + "table_name": {"type": "string", "description": "Name of the table to describe"}, }, - ), - types.Tool( - name="append-insight", - description="Add a business insight to the memo", - inputSchema={ - "type": "object", - "properties": { - "insight": {"type": "string", "description": "Business insight discovered from data analysis"}, - }, - "required": ["insight"], + "required": ["table_name"], + }, + ), + types.Tool( + name="append-insight", + description="Add a business insight to the memo", + inputSchema={ + "type": "object", + "properties": { + "insight": {"type": "string", "description": "Business insight discovered from data analysis"}, }, - ), - ] - - @self.call_tool() - async def handle_call_tool( - name: str, arguments: dict | None - ) -> list[types.TextContent | types.ImageContent | types.EmbeddedResource]: - """Handle tool execution requests""" - try: - if name == "list-tables": - results = self._execute_query( - "SELECT name FROM sqlite_master WHERE type='table'" - ) - return [types.TextContent(type="text", text=str(results))] + "required": ["insight"], + }, + ), + ] - elif name == "describe-table": - if not arguments or "table_name" not in arguments: - raise ValueError("Missing table_name argument") - results = self._execute_query( - f"PRAGMA table_info({arguments['table_name']})" - ) - return [types.TextContent(type="text", text=str(results))] + @server.call_tool() + async def handle_call_tool( + name: str, arguments: dict[str, Any] | None + ) -> list[types.TextContent | types.ImageContent | types.EmbeddedResource]: + """Handle tool execution requests""" + try: + if name == "list-tables": + results = db._execute_query( + "SELECT name FROM sqlite_master WHERE type='table'" + ) + return [types.TextContent(type="text", text=str(results))] + + elif name == "describe-table": + if not arguments or "table_name" not in arguments: + raise ValueError("Missing table_name argument") + results = db._execute_query( + f"PRAGMA table_info({arguments['table_name']})" + ) + return [types.TextContent(type="text", text=str(results))] - elif name == "append-insight": - if not arguments or "insight" not in arguments: - raise ValueError("Missing insight argument") + elif name == "append-insight": + 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,35 +338,34 @@ async def handle_call_tool( 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"]) - return [types.TextContent(type="text", text=str(results))] + if not arguments: + raise ValueError("Missing arguments") - 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"]) - return [types.TextContent(type="text", text=str(results))] + if name == "read-query": + if not arguments["query"].strip().upper().startswith("SELECT"): + raise ValueError("Only SELECT queries are allowed for read-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"]) - return [types.TextContent(type="text", text="Table created successfully")] + elif name == "write-query": + if arguments["query"].strip().upper().startswith("SELECT"): + raise ValueError("SELECT queries are not allowed for write-query") + results = db._execute_query(arguments["query"]) + return [types.TextContent(type="text", text=str(results))] - else: - raise ValueError(f"Unknown tool: {name}") + elif name == "create-table": + if not arguments["query"].strip().upper().startswith("CREATE TABLE"): + raise ValueError("Only CREATE TABLE statements are allowed") + db._execute_query(arguments["query"]) + return [types.TextContent(type="text", text="Table created successfully")] - except sqlite3.Error as e: - return [types.TextContent(type="text", text=f"Database error: {str(e)}")] - except Exception as e: - return [types.TextContent(type="text", text=f"Error: {str(e)}")] + else: + raise ValueError(f"Unknown tool: {name}") -async def main(db_path: str): - logger.info(f"Starting SQLite MCP Server with DB path: {db_path}") - server = McpServer(db_path) + except sqlite3.Error as e: + return [types.TextContent(type="text", text=f"Database error: {str(e)}")] + except Exception as e: + return [types.TextContent(type="text", text=f"Error: {str(e)}")] async with mcp.server.stdio.stdio_server() as (read_stream, write_stream): logger.info("Server running with stdio transport") @@ -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={}, ), ), ) From d5cef5bb7377e43181e516159ea2ff3d5d5fb97b Mon Sep 17 00:00:00 2001 From: Justin Spahr-Summers Date: Thu, 21 Nov 2024 22:26:11 +0000 Subject: [PATCH 3/5] Fix errors --- src/sqlite/src/mcp_server_sqlite/server.py | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/sqlite/src/mcp_server_sqlite/server.py b/src/sqlite/src/mcp_server_sqlite/server.py index 5ca3b8fa..13edcc30 100644 --- a/src/sqlite/src/mcp_server_sqlite/server.py +++ b/src/sqlite/src/mcp_server_sqlite/server.py @@ -8,6 +8,7 @@ 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') @@ -331,12 +332,10 @@ async def handle_call_tool( 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")) - - return [types.TextContent(type="text", text="Insight added to memo")] - if not arguments: - raise ValueError("Missing arguments") + # Notify clients that the memo resource has changed + await self.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") From a636b3129f06f38132a760416f15a314e0d6ef63 Mon Sep 17 00:00:00 2001 From: Justin Spahr-Summers Date: Thu, 21 Nov 2024 22:27:30 +0000 Subject: [PATCH 4/5] Fix README commands --- src/git/README.md | 32 ++++++++++++++++---------------- src/sqlite/README.md | 22 +++++++++++----------- 2 files changed, 27 insertions(+), 27 deletions(-) diff --git a/src/git/README.md b/src/git/README.md index cb2681f7..c5a2dd10 100644 --- a/src/git/README.md +++ b/src/git/README.md @@ -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. diff --git a/src/sqlite/README.md b/src/sqlite/README.md index 5e8e569e..36b63c6e 100644 --- a/src/sqlite/README.md +++ b/src/sqlite/README.md @@ -39,16 +39,16 @@ The server offers six core tools: ```bash # Add the server to your claude_desktop_config.json "mcpServers": { - "sqlite": { - "command": "uv", - "args": [ - "--directory", - "parent_of_servers_repo/servers/src/sqlite", - "run", - "sqlite", - "--db-path", - "~/test.db" - ] - } + "sqlite": { + "command": "uv", + "args": [ + "--directory", + "parent_of_servers_repo/servers/src/sqlite", + "run", + "mcp-server-sqlite", + "--db-path", + "~/test.db" + ] } +} ``` From e63940f76e01d9d37fda2be97617b5f5dced0038 Mon Sep 17 00:00:00 2001 From: Justin Spahr-Summers Date: Thu, 21 Nov 2024 22:29:14 +0000 Subject: [PATCH 5/5] Fix another error --- src/sqlite/src/mcp_server_sqlite/server.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/sqlite/src/mcp_server_sqlite/server.py b/src/sqlite/src/mcp_server_sqlite/server.py index 13edcc30..6124dcae 100644 --- a/src/sqlite/src/mcp_server_sqlite/server.py +++ b/src/sqlite/src/mcp_server_sqlite/server.py @@ -333,7 +333,7 @@ async def handle_call_tool( _ = 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")]