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 Inspector を使用してサーバーに接続できます。
npx @modelcontextprotocol/inspector http://localhost:3003
または、提供されているスクリプトを使用します。
SSEクライアントの例
SSE を使用して MCP Firebird サーバーに接続する方法を示すサンプル クライアントをいくつか提供します。
- HTML/JavaScript : ブラウザベースのクライアントについては
examples/sse-client.html
参照してください。 - Node.js : Node.jsクライアントについては
examples/sse-client.js
参照してください。 - Python : Pythonクライアントについては
examples/sse_client.py
を参照してください
SSE トランスポートの使用に関する詳細なドキュメントについては、 docs/sse-examples.md
を参照してください。
Claude Desktopによる構成
Claude Desktop で Firebird MCP サーバーを使用するには:
次の構成を追加します。
{
"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"
}
- execute-query : データベースで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
}
}
- validate-database : 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ツールは、Firebird の RDB$DESCRIPTION メタデータからコメントを取得し、各フィールドの目的に関する追加のセマンティック コンテキストを提供するため、AI モデルに特に役立ちます。
パフォーマンス分析ツール ( 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
- optimize-query : 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);
パイソン
# 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の設定
STDIO と SSE の両方のトランスポートをサポートする Docker コンテナで MCP Firebird サーバーを実行できます。
Dockerファイル
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コンポーズ
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
Docker化されたMCPサーバーへの接続
クロード・デスクトップ
Docker コンテナを使用するように Claude Desktop の構成を更新します。
{
"mcpServers": {
"mcp-firebird": {
"command": "docker",
"args": [
"exec",
"-i",
"mcp-firebird-stdio",
"node",
"dist/index.js"
],
"type": "stdio"
}
}
}
Webクライアントの場合
http://localhost:3003
の SSE エンドポイントに接続するか、またはhttp://localhost:3005
のプロキシ経由で接続します。
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トランスポートサポート: 堅牢なServer-Sent Events (SSE)トランスポート実装を追加
- プロキシサポート: SSEプロキシ経由の接続のサポートが追加されました
- マルチトランスポートアーキテクチャ: STDIOとSSEトランスポートの両方をサポート
- 強化されたセキュリティ: セキュリティオプションと構成の改善
- Docker サポート: すべてのトランスポート タイプの Docker 構成を更新しました
バージョン 1.0.93 (以前の安定バージョン)
MCP Firebird は、以下の点で大幅に改善されました。
- 強化された TypeScript インターフェース:
- 型の安全性を向上させる新しいインターフェース (FirebirdDatabase、ConfigOptions、DatabaseInfo、TableInfo など)
- すべてのパラメータと戻り値の型指定を厳格化
- エラー処理の改善:
- エラー分類を改善するためのカスタム
FirebirdError
クラス - さまざまなエラー タイプ (接続、構文、権限など) の詳細な検出
- より分かりやすいエラーメッセージでデバッグが容易になります
- 新しい機能とツール:
- API検出用の
get-methods
ツール - テーブルを分析し、クエリを最適化するための新しいプロンプト
- 詳細なテーブル構造のための
describeTable
関数 - シンプルなテーブル名一覧のための
listTables
関数
- より良いドキュメント:
- すべての機能のための包括的なJSDoc
- Firebird固有の情報を含むMCPツールの説明の改善
- Firebird がページ区切りに LIMIT ではなく FIRST/ROWS を使用するという明確な仕様
- セキュリティの改善:
- 明示的なSQLパラメータ検証
- 強化されたSQLインジェクション防止
- テーブルと操作に対する設定可能なアクセス制限
- コード品質:
- 不要なファイル(server.js、server.new.js、test-*.js など)の削除
- よりコンパクトなJSONレスポンス(不要なスペースを削除)
- 一貫したログ記録アプローチ
ユースケース
- AIによるデータ分析:
- 過去の販売傾向を分析する
- 財務データのパターンを特定する
- 取引記録の異常を検出する
- 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
このバージョン:
- 結合前にデータセットを削減する
- 合計を1回だけ計算します
- 推奨インデックスの恩恵を受ける
[クロードは新しいクエリに対して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
を使用してください)
ライセンス
マサチューセッツ工科大学