SQL数据库接口
STDIO基于会话AI的SQL数据库交互工具
基于会话AI的SQL数据库交互工具
A FastMCP server that provides SQL database interaction tools via a conversational AI interface.
This project creates a server that exposes MS SQL Server operations through a conversational AI interface. It uses the FastMCP framework to provide tools for querying and manipulating SQL data, allowing users to interact with databases using natural language.
pip install pyodbc asyncio fastmcp
Ensure you have Microsoft SQL Server installed and the ODBC Driver 17 for SQL Server.
Configure the connection settings in the script:
# Connection parameters SERVER = "server\\instance" # Change to your SQL Server instance DATABASE = "db_name" # Change to your database name
Run the server:
python mcp_sql_server.py
The server will initialize and establish a connection to the specified SQL Server database.
Execute a SQL query and return the results.
query_sql(query: str = None) -> str
SELECT * FROM [dbo].[Table_1]
List all tables available in the database.
list_tables() -> str
Get the structure of a specific table.
describe_table(table_name: str) -> str
table_name
: Name of the table to describeExecute INSERT, UPDATE, DELETE or other non-query SQL statements.
execute_nonquery(sql: str) -> str
sql
: The SQL statement to executeList all available ODBC drivers on the system.
list_odbc_drivers() -> str
Get general information about the connected database.
database_info() -> str
The server uses an asynchronous architecture to avoid blocking operations:
Lifecycle Management: The app_lifespan
context manager handles database connection setup and teardown.
Non-blocking Operations: Database operations run in a separate thread using asyncio.get_event_loop().run_in_executor()
to prevent blocking the main event loop.
Error Handling: All operations include comprehensive error handling with useful error messages.
The server handles various error conditions:
All errors are logged and appropriate error messages are returned to the client.
To add new database tools or modify existing ones, follow the pattern used in the existing tools:
@mcp.tool() async def your_new_tool(ctx: Context, param1: str) -> str: """Documentation for your tool""" try: conn = ctx.request_context.lifespan_context["conn"] if conn is None: return "Database connection is not available." def your_db_operation(): # Your database operations here pass loop = asyncio.get_event_loop() result = await loop.run_in_executor(None, your_db_operation) # Process and return results return "Your result" except Exception as e: return f"Error: {str(e)}"
Common issues:
[Your License Information]
[Your Contact Information]