MCP 파이어버드
Firebird 데이터베이스를 위한 Anthropic의 MCP 프로토콜 구현.
MCP Firebird는 무엇이고, 어떤 용도로 사용되나요?
MCP Firebird는 Firebird SQL 데이터베이스 용 Anthropic의 모델 컨텍스트 프로토콜(MCP)을 구현하는 서버입니다. Claude와 같은 대규모 언어 모델(LLM)이 Firebird 데이터베이스의 데이터에 안전하고 통제된 방식으로 접근, 분석 및 조작할 수 있도록 지원합니다.
아래에서 사용 사례와 예를 확인할 수 있습니다.
설치
Smithery를 통해 설치
Smithery 를 통해 Claude Desktop에 MCP Firebird를 자동으로 설치하려면:
지엑스피1
수동 설치
# 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(Server-Sent Events) 전송 사용
MCP Firebird 서버는 또한 클라이언트가 HTTP를 통해 연결할 수 있도록 하는 SSE 전송을 지원합니다.
# 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"
}
- backup-database : 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 도구는 특히 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
- optimize-query : SQL 쿼리 최적화
Optimize: SELECT * FROM EMPLOYEES WHERE LAST_NAME = 'Smith'
- generate-sql : 설명으로부터 SQL 생성
Generate a query to get the 10 best-selling products
다양한 언어에서의 사용법
타입스크립트/자바스크립트
// 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 서버를 실행할 수 있습니다.
도커파일
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"]
도커 컴포즈
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 서버에 연결
클로드 데스크톱과 함께
Docker 컨테이너를 사용하도록 Claude Desktop 구성을 업데이트하세요.
{
"mcpServers": {
"mcp-firebird": {
"command": "docker",
"args": [
"exec",
"-i",
"mcp-firebird-stdio",
"node",
"dist/index.js"
],
"type": "stdio"
}
}
}
웹 클라이언트를 사용하여
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 전송 지원 : 강력한 SSE(Server-Sent Events) 전송 구현이 추가되었습니다.
- 프록시 지원 : 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
이 버전:
- 조인하기 전에 데이터 세트를 줄입니다.
- 합계를 한 번만 계산합니다
- 추천 인덱스를 활용하면 도움이 됩니다.
[Claude는 새로운 쿼리에 MCP Firebird의 분석-쿼리-성능 도구를 사용합니다.]
최적화 후:
- 평균 실행 시간: 320ms(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 Desktop을 다시 시작하세요
claude_desktop_config.json
에서 구성을 확인하세요.- 데이터베이스 경로가 절대 경로인지 확인하세요.
- STDIO 문제 :
- 표준 출력이 리디렉션되지 않는지 확인하세요.
- 디버깅을 위해
console.log
사용하지 마세요(대신 console.error
사용하세요)
특허
MIT