MCP 火鸟
为 Firebird 数据库实现 Anthropic 的 MCP 协议。
MCP Firebird 是什么以及它有什么用途?
MCP Firebird 是一个为Firebird SQL 数据库实现 Anthropic模型上下文协议 (MCP)的服务器。它允许像 Claude 这样的大型语言模型 (LLM) 以安全且可控的方式访问、分析和操作 Firebird 数据库中的数据。
您将在下面找到用例和示例。
安装
通过 Smithery 安装
要通过Smithery自动为 Claude Desktop 安装 MCP Firebird:
npx -y @smithery/cli install @PuroDelphi/mcpFirebird --client claude
手动安装
# Global installation
npm install -g mcp-firebird
# Project installation
npm install mcp-firebird
配置
环境变量
您可以使用环境变量配置服务器:
# Basic configuration
export FIREBIRD_HOST=localhost
export FIREBIRD_PORT=3050
export FIREBIRD_DATABASE=/path/to/database.fdb
export FIREBIRD_USER=SYSDBA
export FIREBIRD_PASSWORD=masterkey
export FIREBIRD_ROLE=undefined # Optional
# Directory configuration (alternative)
export FIREBIRD_DATABASE_DIR=/path/to/databases # Directory with databases
# Logging configuration
export LOG_LEVEL=info # Options: debug, info, warn, error
您可以在项目根目录中创建一个.env
文件来设置这些变量。我们提供了一个.env.example
文件作为模板。
示例 .env 文件
FIREBIRD_HOST=localhost
FIREBIRD_PORT=3050
FIREBIRD_DATABASE=F:\Proyectos\SAI\EMPLOYEE.FDB
FIREBIRD_USER=SYSDBA
FIREBIRD_PASSWORD=masterkey
LOG_LEVEL=info
与 npx 一起使用
您可以直接使用 npx 运行服务器:
npx mcp-firebird --host localhost --port 3050 --database /path/to/database.fdb --user SYSDBA --password masterkey
使用 SSE(服务器发送事件)传输
MCP Firebird 服务器还支持 SSE 传输,允许客户端通过 HTTP 进行连接:
# Set the transport type to SSE in your .env file
TRANSPORT_TYPE=sse
SSE_PORT=3003
# Run the server with SSE transport
npm run sse
然后您可以使用 MCP 检查器连接到服务器:
npx @modelcontextprotocol/inspector http://localhost:3003
或者使用提供的脚本:
SSE 客户端示例
我们提供了几个示例客户端,演示如何使用 SSE 连接到 MCP Firebird 服务器:
- HTML/JavaScript :请参阅基于浏览器的客户端的
examples/sse-client.html
- Node.js :请参阅
examples/sse-client.js
了解 Node.js 客户端 - Python :请参阅
examples/sse_client.py
了解 Python 客户端
有关使用 SSE 传输的详细文档,请参阅docs/sse-examples.md
。
使用 Claude Desktop 进行配置
要将 Firebird MCP 服务器与 Claude Desktop 一起使用:
添加以下配置:
{
"mcpServers": {
"mcp-firebird": {
"command": "npx",
"args": [
"mcp-firebird",
"--host",
"localhost",
"--port",
"3050",
"--database",
"C:\\Databases\\example.fdb",
"--user",
"SYSDBA",
"--password",
"masterkey"
],
"type": "stdio"
}
}
}
资源和功能
MCP Firebird 服务器提供:
- 数据库:所有可用数据库的列表
- 表:数据库中所有表的列表
- 视图:数据库中所有视图的列表
- 存储过程:访问数据库中的过程
- 表模式:每个表的详细结构
- 数据:访问表数据
- 性能分析:分析查询执行时间和性能指标
- 执行计划分析:获取并分析SQL执行计划
- 索引建议:识别可以提高性能的缺失索引
- 数据库备份和恢复:创建和恢复数据库备份
- 数据库验证:检查数据库完整性并修复错误
- 增强的安全选项:数据屏蔽、审计日志和资源限制
可用工具
- list-tables :列出数据库中的所有表
{} // No parameters required
- describe-table :描述表的结构
{
"tableName": "EMPLOYEES"
}
- 执行查询:在数据库中执行 SQL 查询
{
"sql": "SELECT * FROM EMPLOYEES WHERE DEPARTMENT_ID = 10",
"params": [] // Optional parameters for prepared queries
}
- get-field-descriptions :获取字段描述
{
"tableName": "EMPLOYEES"
}
- analyze-query-performance :分析 SQL 查询的性能
{
"sql": "SELECT * FROM EMPLOYEES WHERE DEPARTMENT_ID = 10",
"params": [], // Optional parameters for prepared queries
"iterations": 3 // Optional number of iterations for averaging (default: 3)
}
- get-execution-plan :获取 SQL 查询的执行计划
{
"sql": "SELECT * FROM EMPLOYEES WHERE DEPARTMENT_ID = 10",
"params": [] // Optional parameters for prepared queries
}
- analyze-missing-indexes :分析 SQL 查询以识别缺失的索引
{
"sql": "SELECT * FROM EMPLOYEES WHERE DEPARTMENT_ID = 10"
}
- 备份数据库:创建 Firebird 数据库的备份
{
"backupPath": "C:\\backups\\mydb_backup.fbk",
"options": {
"format": "gbak", // "gbak" (full backup) or "nbackup" (incremental)
"compress": true, // Whether to compress the backup
"metadata_only": false, // Whether to backup only metadata (no data)
"verbose": true // Whether to show detailed progress
}
}
- restore-database :从备份恢复 Firebird 数据库
{
"backupPath": "C:\\backups\\mydb_backup.fbk",
"targetPath": "C:\\databases\\restored_db.fdb",
"options": {
"replace": true, // Whether to replace the target database if it exists
"pageSize": 4096, // Page size for the restored database
"verbose": true // Whether to show detailed progress
}
}
- 验证数据库:验证 Firebird 数据库的完整性
{
"options": {
"checkData": true, // Whether to validate data integrity
"checkIndexes": true, // Whether to validate indexes
"fixErrors": false, // Whether to attempt to fix errors
"verbose": true // Whether to show detailed progress
}
}
get-field-descriptions工具对于 AI 模型特别有用,因为它从 Firebird 的 RDB$DESCRIPTION 元数据中检索注释,提供有关每个字段用途的额外语义上下文。
性能分析工具( analyze-query-performance 、 get-execution-plan和analyze-missing-indexes )通过提供对执行时间、执行计划和索引建议的洞察来帮助优化数据库查询。
数据库管理工具( backup-database 、 restore-database和validate-database )提供数据库维护和灾难恢复功能。
可用提示
- query-data :使用自然语言查询数据
Find all employees in the sales department hired in 2023
- analyze-table :分析表的结构
Analyze the EMPLOYEES table and explain its structure
- 优化查询:优化 SQL 查询
Optimize: SELECT * FROM EMPLOYEES WHERE LAST_NAME = 'Smith'
- generate-sql :根据描述生成 SQL
Generate a query to get the 10 best-selling products
不同语言的使用
TypeScript/JavaScript
// Example with TypeScript
import { McpClient, ChildProcessTransport } from '@modelcontextprotocol/sdk';
import { spawn } from 'child_process';
async function main() {
// Start the MCP server process
const serverProcess = spawn('npx', [
'mcp-firebird',
'--database', '/path/to/database.fdb',
'--user', 'SYSDBA',
'--password', 'masterkey'
]);
// Create a transport and an MCP client
const transport = new ChildProcessTransport(serverProcess);
const client = new McpClient(transport);
try {
// Get server information
const serverInfo = await client.getServerInfo();
console.log('MCP Server:', serverInfo);
// List available tables
const tablesResult = await client.executeTool('list-tables', {});
console.log('Available tables:', tablesResult);
// Execute an SQL query
const queryResult = await client.executeTool('execute-query', {
sql: 'SELECT FIRST 10 * FROM EMPLOYEES'
});
console.log('Query results:', queryResult);
// Use a prompt to generate SQL
const sqlGeneration = await client.executePrompt('generate-sql', {
description: 'Get all premium customers'
});
console.log('Generated SQL:', sqlGeneration);
} catch (error) {
console.error('Error:', error);
} finally {
// Close the server process
serverProcess.kill();
}
}
main().catch(console.error);
Python
# Example with Python
import json
import subprocess
from subprocess import PIPE
class McpFirebirdClient:
def __init__(self, database_path, user='SYSDBA', password='masterkey'):
# Start the MCP server process
self.process = subprocess.Popen(
['npx', 'mcp-firebird', '--database', database_path, '--user', user, '--password', password],
stdin=PIPE,
stdout=PIPE,
stderr=PIPE,
text=True,
bufsize=1
)
def send_request(self, method, params={}):
request = {
'id': 1,
'method': method,
'params': params
}
# Send the request to the server
self.process.stdin.write(json.dumps(request) + '\n')
self.process.stdin.flush()
# Read the response
response_line = self.process.stdout.readline()
while not response_line.strip() or response_line.startswith('['):
response_line = self.process.stdout.readline()
# Parse and return the JSON response
return json.loads(response_line)
def get_server_info(self):
return self.send_request('getServerInfo')
def list_tables(self):
return self.send_request('executeTool', {'name': 'list-tables', 'args': {}})
def execute_query(self, sql, params=[]):
return self.send_request('executeTool', {
'name': 'execute-query',
'args': {'sql': sql, 'params': params}
})
def generate_sql(self, description):
return self.send_request('executePrompt', {
'name': 'generate-sql',
'args': {'description': description}
})
def close(self):
self.process.terminate()
# Client usage
client = McpFirebirdClient('/path/to/database.fdb')
try:
# Get server information
server_info = client.get_server_info()
print(f"MCP Server: {server_info}")
# List tables
tables = client.list_tables()
print(f"Available tables: {tables}")
# Execute a query
results = client.execute_query("SELECT FIRST 10 * FROM EMPLOYEES")
print(f"Results: {results}")
# Generate SQL
sql = client.generate_sql("List the best-selling products")
print(f"Generated SQL: {sql}")
finally:
client.close()
德尔斐和拉撒路
// Example with Delphi
program McpFirebirdClient;
{$APPTYPE CONSOLE}
uses
System.SysUtils, System.Classes, System.JSON, System.Net.HttpClient,
System.Diagnostics, System.IOUtils;
type
TMcpFirebirdClient = class
private
FProcess: TProcess; //For Delphi change to TProcessDelphi and add https://github.com/ferruhkoroglu/TProcessDelphi
FRequestId: Integer;
function SendRequest(const Method: string; const Params: TJSONObject = nil): TJSONObject;
function ReadResponse: string;
public
constructor Create(const DatabasePath, User, Password: string);
destructor Destroy; override;
function GetServerInfo: TJSONObject;
function ListTables: TJSONObject;
function ExecuteQuery(const SQL: string; Params: TArray<Variant> = nil): TJSONObject;
function GenerateSQL(const Description: string): TJSONObject;
end;
constructor TMcpFirebirdClient.Create(const DatabasePath, User, Password: string);
begin
inherited Create;
FRequestId := 1;
// Create and configure the process
FProcess := TProcess.Create(nil);
FProcess.Executable := 'npx';
FProcess.Parameters.Add('mcp-firebird');
FProcess.Parameters.Add('--database');
FProcess.Parameters.Add(DatabasePath);
FProcess.Parameters.Add('--user');
FProcess.Parameters.Add(User);
FProcess.Parameters.Add('--password');
FProcess.Parameters.Add(Password);
FProcess.Options := [poUsePipes, poStderrToOutPut];
FProcess.Execute;
// Wait for the server to start
Sleep(2000);
end;
destructor TMcpFirebirdClient.Destroy;
begin
FProcess.Free;
inherited;
end;
function TMcpFirebirdClient.SendRequest(const Method: string; const Params: TJSONObject = nil): TJSONObject;
var
Request: TJSONObject;
RequestStr, ResponseStr: string;
begin
// Create the JSON request
Request := TJSONObject.Create;
try
Request.AddPair('id', TJSONNumber.Create(FRequestId));
Inc(FRequestId);
Request.AddPair('method', Method);
if Assigned(Params) then
Request.AddPair('params', Params)
else
Request.AddPair('params', TJSONObject.Create);
RequestStr := Request.ToString + #10;
// Send the request to the process
FProcess.Input.Write(RequestStr[1], Length(RequestStr) * 2);
// Read the response
ResponseStr := ReadResponse;
Result := TJSONObject.ParseJSONValue(ResponseStr) as TJSONObject;
finally
Request.Free;
end;
end;
function TMcpFirebirdClient.ReadResponse: string;
var
Buffer: TBytes;
BytesRead: Integer;
ResponseStr: string;
begin
SetLength(Buffer, 4096);
ResponseStr := '';
repeat
BytesRead := FProcess.Output.Read(Buffer[0], Length(Buffer));
if BytesRead > 0 then
begin
SetLength(Buffer, BytesRead);
ResponseStr := ResponseStr + TEncoding.UTF8.GetString(Buffer);
end;
until BytesRead = 0;
Result := ResponseStr;
end;
function TMcpFirebirdClient.GetServerInfo: TJSONObject;
begin
Result := SendRequest('getServerInfo');
end;
function TMcpFirebirdClient.ListTables: TJSONObject;
var
Params: TJSONObject;
begin
Params := TJSONObject.Create;
try
Params.AddPair('name', 'list-tables');
Params.AddPair('args', TJSONObject.Create);
Result := SendRequest('executeTool', Params);
finally
Params.Free;
end;
end;
function TMcpFirebirdClient.ExecuteQuery(const SQL: string; Params: TArray<Variant> = nil): TJSONObject;
var
RequestParams, Args: TJSONObject;
ParamsArray: TJSONArray;
I: Integer;
begin
RequestParams := TJSONObject.Create;
Args := TJSONObject.Create;
ParamsArray := TJSONArray.Create;
try
// Configure the arguments
Args.AddPair('sql', SQL);
if Length(Params) > 0 then
begin
for I := 0 to Length(Params) - 1 do
begin
case VarType(Params[I]) of
varInteger: ParamsArray.Add(TJSONNumber.Create(Integer(Params[I])));
varDouble: ParamsArray.Add(TJSONNumber.Create(Double(Params[I])));
varBoolean: ParamsArray.Add(TJSONBool.Create(Boolean(Params[I])));
else ParamsArray.Add(String(Params[I]));
end;
end;
end;
Args.AddPair('params', ParamsArray);
RequestParams.AddPair('name', 'execute-query');
RequestParams.AddPair('args', Args);
Result := SendRequest('executeTool', RequestParams);
finally
RequestParams.Free;
end;
end;
function TMcpFirebirdClient.GenerateSQL(const Description: string): TJSONObject;
var
RequestParams, Args: TJSONObject;
begin
RequestParams := TJSONObject.Create;
Args := TJSONObject.Create;
try
Args.AddPair('description', Description);
RequestParams.AddPair('name', 'generate-sql');
RequestParams.AddPair('args', Args);
Result := SendRequest('executePrompt', RequestParams);
finally
RequestParams.Free;
end;
end;
var
Client: TMcpFirebirdClient;
ServerInfo, Tables, QueryResults, GeneratedSQL: TJSONObject;
begin
try
WriteLn('Starting MCP Firebird client...');
// Create the client
Client := TMcpFirebirdClient.Create('C:\Databases\example.fdb', 'SYSDBA', 'masterkey');
try
// Get server information
ServerInfo := Client.GetServerInfo;
WriteLn('Server information: ', ServerInfo.ToString);
// List tables
Tables := Client.ListTables;
WriteLn('Available tables: ', Tables.ToString);
// Execute a query
QueryResults := Client.ExecuteQuery('SELECT FIRST 10 * FROM EMPLOYEES');
WriteLn('Query results: ', QueryResults.ToString);
// Generate SQL
GeneratedSQL := Client.GenerateSQL('Get all premium customers');
WriteLn('Generated SQL: ', GeneratedSQL.ToString);
finally
Client.Free;
end;
except
on E: Exception do
WriteLn('Error: ', E.Message);
end;
WriteLn('Press ENTER to exit...');
ReadLn;
end.
Docker 配置
您可以在 Docker 容器中运行 MCP Firebird 服务器,并支持 STDIO 和 SSE 传输:
Dockerfile
FROM node:20-alpine
# No external Firebird client needed as MCP Firebird includes its own Node.js client
# Create application directory
WORKDIR /app
# Copy project files
COPY package*.json ./
COPY tsconfig.json ./
# Install dependencies
RUN npm install
# Copy source code
COPY src/ ./src/
COPY run-sse-server.js ./
COPY run-sse-proxy.js ./
COPY run-inspector.cjs ./
COPY run-inspector.js ./
# Compile the TypeScript project
RUN npm run build
# Expose port for SSE transport
EXPOSE 3003
# Set default environment variables
ENV FIREBIRD_HOST=firebird-db
ENV FIREBIRD_PORT=3050
ENV FIREBIRD_USER=SYSDBA
ENV FIREBIRD_PASSWORD=masterkey
ENV FIREBIRD_DATABASE=/firebird/data/database.fdb
ENV TRANSPORT_TYPE=stdio
ENV SSE_PORT=3003
ENV LOG_LEVEL=info
# Start command (can be overridden by docker-compose)
CMD ["node", "dist/index.js"]
Docker Compose
version: '3.8'
services:
# Firebird database server
firebird-db:
image: jacobalberty/firebird:3.0
environment:
ISC_PASSWORD: masterkey
FIREBIRD_DATABASE: database.fdb
FIREBIRD_USER: SYSDBA
volumes:
- firebird-data:/firebird/data
ports:
- "3050:3050"
networks:
- mcp-network
# MCP Firebird server with STDIO transport (for Claude Desktop)
mcp-firebird-stdio:
build:
context: .
dockerfile: Dockerfile
environment:
FIREBIRD_HOST: firebird-db
FIREBIRD_PORT: 3050
FIREBIRD_USER: SYSDBA
FIREBIRD_PASSWORD: masterkey
FIREBIRD_DATABASE: /firebird/data/database.fdb
TRANSPORT_TYPE: stdio
depends_on:
- firebird-db
networks:
- mcp-network
# For use with Claude Desktop, expose STDIO
stdin_open: true
tty: true
# MCP Firebird server with SSE transport (for web clients)
mcp-firebird-sse:
build:
context: .
dockerfile: Dockerfile
environment:
FIREBIRD_HOST: firebird-db
FIREBIRD_PORT: 3050
FIREBIRD_USER: SYSDBA
FIREBIRD_PASSWORD: masterkey
FIREBIRD_DATABASE: /firebird/data/database.fdb
TRANSPORT_TYPE: sse
SSE_PORT: 3003
ports:
- "3003:3003"
depends_on:
- firebird-db
networks:
- mcp-network
command: node run-sse-server.js
# SSE Proxy (optional, for clients that need proxy support)
mcp-sse-proxy:
build:
context: .
dockerfile: Dockerfile
environment:
MCP_SERVER_URL: http://mcp-firebird-sse:3003
PORT: 3005
ports:
- "3005:3005"
depends_on:
- mcp-firebird-sse
networks:
- mcp-network
command: node run-sse-proxy.js
networks:
mcp-network:
driver: bridge
volumes:
firebird-data:
使用 Docker 运行
# Build and run with Docker Compose
docker compose up -d
# Run only the STDIO version (for Claude Desktop)
docker compose up -d mcp-firebird-stdio
# Run only the SSE version (for web clients)
docker compose up -d mcp-firebird-sse
# Run the SSE version with proxy (for clients that need proxy support)
docker compose up -d mcp-firebird-sse mcp-sse-proxy
# Check logs
docker compose logs -f mcp-firebird-sse
# Stop services
docker compose down
连接到 Dockerized MCP 服务器
使用 Claude Desktop
更新您的 Claude Desktop 配置以使用 Docker 容器:
{
"mcpServers": {
"mcp-firebird": {
"command": "docker",
"args": [
"exec",
"-i",
"mcp-firebird-stdio",
"node",
"dist/index.js"
],
"type": "stdio"
}
}
}
使用 Web 客户端
通过http://localhost:3003
或代理http://localhost:3005
连接到 SSE 端点。
使用 MCP 检查器
# Connect directly to the SSE server
npx @modelcontextprotocol/inspector http://localhost:3003
# Or connect through the proxy
npx @modelcontextprotocol/inspector http://localhost:3005
最近更新
版本 2.0.5
MCP Firebird 已显著增强:
- SSE 传输支持:添加了强大的服务器发送事件 (SSE) 传输实现
- 代理支持:增加了通过 SSE 代理连接的支持
- 多传输架构:支持 STDIO 和 SSE 传输
- 增强的安全性:改进的安全选项和配置
- Docker 支持:更新了所有传输类型的 Docker 配置
版本 1.0.93(之前的稳定版本)
MCP Firebird 已显著改进:
- 增强的 TypeScript 接口:
- 新的接口具有更好的类型安全性(FirebirdDatabase、ConfigOptions、DatabaseInfo、TableInfo 等)
- 对所有参数和返回值进行更严格的类型化
- 改进的错误处理:
- 自定义
FirebirdError
类以实现更好的错误分类 - 详细检测不同的错误类型(连接、语法、权限等)
- 更多信息错误消息,更易于调试
- 新功能和工具:
- 用于 API 发现的
get-methods
工具 - 用于分析表和优化查询的新提示
describeTable
函数获取详细的表结构listTables
函数用于简单的表名列表
- 更好的文档:
- 所有功能的综合 JSDoc
- 改进了 MCP 工具描述,添加了 Firebird 特定的信息
- 明确说明 Firebird 使用 FIRST/ROWS 而不是 LIMIT 进行分页
- 安全改进:
- 显式 SQL 参数验证
- 增强的 SQL 注入预防
- 可配置表和操作的访问限制
- 代码质量:
- 删除不必要的文件(server.js、server.new.js、test-*.js 等)
- 更紧凑的 JSON 响应(删除了不必要的空格)
- 一致的日志记录方法
用例
- 人工智能数据分析:
- 分析历史销售趋势
- 识别财务数据中的模式
- 检测交易记录中的异常
- SQL查询生成:
- 根据自然语言描述创建复杂查询
- 优化现有查询以提高性能
- 在不同的 SQL 方言之间转换查询
- 自动化文档:
- 生成有关数据库结构的文档
- 解释表和模式之间的关系
- 创建详细的数据字典
- 发展援助:
- 建议索引以提高性能
- 提出模式规范化
- 帮助系统间数据迁移
销售分析使用示例
与克劳德的互动:
User: Connect to my Firebird database and analyze sales trends by region in the last quarter.
Claude: I'll connect to your Firebird database to analyze regional sales trends.
[Claude uses MCP Firebird to execute several SQL queries]
Based on data from the last quarter, I've identified the following trends:
1. The North region has experienced 12.5% growth compared to the previous quarter
2. The South region shows a 3.2% decrease in electronics products
3. The "Laptop Pro X" product is the best-selling across all regions
4. Sales in the East region show a cyclical pattern with peaks on weekends
Graphically, the distribution of sales by region is:
[Graph generated by Claude based on the data]
Would you like to delve deeper into any specific region or product category?
查询优化和性能分析示例
User: I have this query that's running slowly, can you optimize it?
SELECT c.CUSTOMER_NAME, SUM(o.ORDER_TOTAL)
FROM CUSTOMERS c
JOIN ORDERS o ON c.CUSTOMER_ID = o.CUSTOMER_ID
WHERE o.ORDER_DATE > '2024-01-01'
GROUP BY c.CUSTOMER_NAME
ORDER BY SUM(o.ORDER_TOTAL) DESC
Claude: I'll analyze this query to optimize it. First, let me check the execution plan and performance.
[Claude uses MCP Firebird's get-execution-plan tool]
The execution plan shows:
- Full table scan on ORDERS table
- Nested loop join with CUSTOMERS
- Sorting operation for ORDER BY clause
- No indexes being used for the date filtering
[Claude uses MCP Firebird's analyze-query-performance tool]
Performance analysis:
- Average execution time: 1250ms
- Minimum execution time: 1150ms
- Maximum execution time: 1380ms
- Rows returned: 487
[Claude uses MCP Firebird's analyze-missing-indexes tool]
Missing index analysis recommends:
- CREATE INDEX IDX_ORDERS_ORDER_DATE ON ORDERS (ORDER_DATE);
- CREATE INDEX IDX_ORDERS_CUSTOMER_ID ON ORDERS (CUSTOMER_ID);
Based on these analyses, I've identified several optimization opportunities:
1. The current query doesn't efficiently use indexes
2. The calculation of SUM(o.ORDER_TOTAL) is performed twice
3. We should add indexes on the JOIN and WHERE columns
Here's the optimized version:
```sql
SELECT c.CUSTOMER_NAME, total_sales
FROM CUSTOMERS c
JOIN (
SELECT CUSTOMER_ID, SUM(ORDER_TOTAL) as total_sales
FROM ORDERS
WHERE ORDER_DATE > '2024-01-01'
GROUP BY CUSTOMER_ID
) o ON c.CUSTOMER_ID = o.CUSTOMER_ID
ORDER BY total_sales DESC
此版本:
- 在连接之前减少数据集
- 仅计算一次总和
- 将受益于推荐的指数
[Claude 使用 MCP Firebird 的分析查询性能工具对新查询进行分析]
优化后:
- 平均执行时间:320毫秒(快74%)
- 返回行数:487(相同结果)
我建议创建这些索引以进一步提高性能:
CREATE INDEX IDX_ORDERS_ORDER_DATE ON ORDERS (ORDER_DATE);
CREATE INDEX IDX_ORDERS_CUSTOMER_ID ON ORDERS (CUSTOMER_ID);
## Integration with AI Agents
### Claude in the Terminal
You can use the MCP Firebird server with Claude in the terminal:
```bash
# Start the MCP server in one terminal
npx mcp-firebird --database /path/to/database.fdb --user SYSDBA --password masterkey
# In another terminal, use anthropic CLI with MCP
anthropic messages create \
--model claude-3-opus-20240229 \
--max-tokens 4096 \
--mcp "npx mcp-firebird --database /path/to/database.fdb --user SYSDBA --password masterkey" \
--message "Analyze the structure of my Firebird database"
其他AI代理
MCP Firebird 服务器与任何实现 MCP 协议的代理兼容,只需提供以下命令即可启动服务器:
npx mcp-firebird --database /path/to/database.fdb --user SYSDBA --password masterkey
安全
MCP Firebird 服务器实施全面的安全措施:
- 使用 Zod 模式进行输入验证
- SQL 查询清理以防止注入攻击
- 数据库连接的安全凭证处理
- 通过参数化查询预防 SQL 注入
- 限制 DROP 和 TRUNCATE 等破坏性操作
- 查询结果中敏感信息的数据屏蔽
- 对所有数据库操作**进行审计日志记录,**以确保安全性和合规性
- 行级安全性,根据安全规则过滤查询结果
- 资源限制以防止滥用和 DoS 攻击
- 限制速率以控制每个会话的查询数量
安全配置
您可以使用 JSON 配置文件配置安全选项。在项目根目录中创建一个名为security.json
的文件:
{
"security": {
"allowedTables": ["EMPLOYEES", "DEPARTMENTS"],
"forbiddenTables": ["USERS", "PASSWORDS"],
"allowedOperations": ["SELECT", "EXECUTE"],
"forbiddenOperations": ["DROP", "TRUNCATE", "ALTER"],
"maxRows": 1000,
"queryTimeout": 5000,
"dataMasking": [
{
"columns": ["CREDIT_CARD", "SSN"],
"pattern": "\\d{4}-\\d{4}-\\d{4}-\\d{4}",
"replacement": "XXXX-XXXX-XXXX-$&"
}
],
"rowFilters": {
"EMPLOYEES": "DEPARTMENT_ID = 10"
},
"audit": {
"enabled": true,
"destination": "file",
"auditFile": "./logs/audit.log",
"detailLevel": "medium",
"logQueries": true
},
"resourceLimits": {
"maxRowsPerQuery": 5000,
"maxResponseSize": 5242880,
"maxQueryCpuTime": 10000,
"maxQueriesPerSession": 100,
"rateLimit": {
"queriesPerMinute": 60,
"burstLimit": 20
}
},
"authorization": {
"type": "basic",
"rolePermissions": {
"admin": {
"allTablesAllowed": true,
"operations": ["SELECT", "INSERT", "UPDATE", "DELETE"]
},
"user": {
"tables": ["EMPLOYEES", "DEPARTMENTS"],
"operations": ["SELECT"]
}
}
}
}
}
然后在启动服务器时指定配置文件的路径:
export SECURITY_CONFIG_PATH=./security.json
调试和故障排除
启用调试模式:
常见问题
- 数据库连接错误:
- 验证凭据和数据库路径
- 确保 Firebird 服务器正在运行
- 检查用户是否具有足够的权限
- 服务器未出现在 Claude Desktop 中:
- 重启Claude桌面
- 验证
claude_desktop_config.json
中的配置 - 确保数据库路径是绝对路径
- STDIO问题:
- 确保标准输出未被重定向
- 不要使用
console.log
进行调试(而是使用console.error
)
执照
麻省理工学院