OPENAI.md•6.54 kB
# OpenAI統合ガイド
## HTTPモードでOpenAIから利用する
Universal MCP ServerはHTTPモードでOpenAIのFunction Callingと統合できます。
## セットアップ
### 1. サーバーの起動(HTTPモード)
```bash
# ビルド
npm run build
# 認証なしで起動(開発用)
MCP_MODE=http MCP_HTTP_PORT=3000 npm start:http
# 認証ありで起動(推奨)
MCP_MODE=http MCP_HTTP_PORT=3000 MCP_API_KEY=your-secret-key npm start:http:auth
```
### 2. ngrokでトンネル作成(外部アクセス用)
```bash
ngrok http 3000
```
出力されたURLをメモします(例: `https://xxxx.ngrok-free.app`)
## エンドポイント
| エンドポイント | メソッド | 説明 |
|--------------|---------|------|
| `/health` | GET | ヘルスチェック |
| `/info` | GET | サーバー情報 |
| `/sse` | GET | SSE接続(MCP通信) |
| `/message` | POST | メッセージ送信 |
## OpenAI Python SDKでの使用例
### インストール
```bash
pip install openai requests
```
### サンプルコード
```python
import openai
import requests
import json
# 設定
NGROK_URL = "https://your-ngrok-url.ngrok-free.app"
API_KEY = "your-secret-key" # 認証なしの場合は None
# OpenAI APIキー
openai.api_key = "your-openai-api-key"
# MCPサーバーのツール情報を取得
headers = {}
if API_KEY:
headers["Authorization"] = f"Bearer {API_KEY}"
response = requests.get(f"{NGROK_URL}/info", headers=headers)
server_info = response.json()
print("Server Info:", json.dumps(server_info, indent=2))
# OpenAIのFunction Calling用のツール定義
tools = [
{
"type": "function",
"function": {
"name": "write_file",
"description": "Write content to a file",
"parameters": {
"type": "object",
"properties": {
"key": {
"type": "string",
"description": "The file key/name"
},
"content": {
"type": "string",
"description": "The content to write"
}
},
"required": ["key", "content"]
}
}
},
{
"type": "function",
"function": {
"name": "read_file",
"description": "Read a file by key",
"parameters": {
"type": "object",
"properties": {
"key": {
"type": "string",
"description": "The file key to read"
}
},
"required": ["key"]
}
}
},
{
"type": "function",
"function": {
"name": "search_files",
"description": "Search for files containing specific text",
"parameters": {
"type": "object",
"properties": {
"query": {
"type": "string",
"description": "The text to search for"
}
},
"required": ["query"]
}
}
}
]
# OpenAI APIコール
response = openai.chat.completions.create(
model="gpt-4",
messages=[
{"role": "user", "content": "Create a file called 'test.txt' with content 'Hello from OpenAI!'"}
],
tools=tools,
tool_choice="auto"
)
# Function Callの処理
if response.choices[0].message.tool_calls:
for tool_call in response.choices[0].message.tool_calls:
function_name = tool_call.function.name
arguments = json.loads(tool_call.function.arguments)
print(f"Calling function: {function_name}")
print(f"Arguments: {arguments}")
# MCPサーバーにリクエスト送信(SSE経由)
# 注意: 実際の実装では適切なMCPクライアントを使用してください
```
## Node.js/TypeScriptでの使用例
```typescript
import OpenAI from 'openai';
import axios from 'axios';
const NGROK_URL = 'https://your-ngrok-url.ngrok-free.app';
const API_KEY = 'your-secret-key'; // 認証なしの場合は undefined
const openai = new OpenAI({
apiKey: process.env.OPENAI_API_KEY,
});
// ツール定義
const tools: OpenAI.Chat.Completions.ChatCompletionTool[] = [
{
type: 'function',
function: {
name: 'write_file',
description: 'Write content to a file',
parameters: {
type: 'object',
properties: {
key: {
type: 'string',
description: 'The file key/name',
},
content: {
type: 'string',
description: 'The content to write',
},
},
required: ['key', 'content'],
},
},
},
];
async function main() {
const response = await openai.chat.completions.create({
model: 'gpt-4',
messages: [
{
role: 'user',
content: 'Create a file called "hello.txt" with content "Hello World"',
},
],
tools,
tool_choice: 'auto',
});
// Function Callの処理
const message = response.choices[0].message;
if (message.tool_calls) {
for (const toolCall of message.tool_calls) {
console.log('Function:', toolCall.function.name);
console.log('Arguments:', toolCall.function.arguments);
// MCPサーバーと通信する実装が必要
}
}
}
main();
```
## curlでのテスト
```bash
# ヘルスチェック
curl https://your-ngrok-url.ngrok-free.app/health
# サーバー情報(認証あり)
curl -H "Authorization: Bearer your-secret-key" \
https://your-ngrok-url.ngrok-free.app/info
# SSE接続テスト
curl -H "Authorization: Bearer your-secret-key" \
-N https://your-ngrok-url.ngrok-free.app/sse
```
## 注意事項
1. **認証の推奨**: 本番環境では必ずAPIキーを設定してください
2. **HTTPS必須**: ngrokは自動的にHTTPSを提供します
3. **レート制限**: 大量リクエストには適切なレート制限を実装してください
4. **エラーハンドリング**: 接続エラーやタイムアウトを適切に処理してください
## 完全なMCPクライアント実装
MCPプロトコルの完全な実装には、SSEクライアントとJSON-RPC 2.0の処理が必要です。
詳細は `@modelcontextprotocol/sdk` のクライアントドキュメントを参照してください。