Model Context Protocol(MCP)
カスタム MCP サーバーを作成し、AI エージェントが標準の MCP プロトコルを介してバックエンドのツールにアクセスできるようにします。
MCP を使用する理由
AI エージェントが外部サーバーでホストされているツールを呼び出す必要がある場合や、MCP 対応クライアントが検出して呼び出せるツールとして、独自のバックエンドロジックを公開したい場合があります。
MCP がなければ、エージェントとツールの接続ごとにカスタムの統合ロジックを構築する必要があります。MCP を使用すると、サーバー上でツールを定義し、対応する任意のエージェントが標準プロトコルを介してツールを検出し、呼び出せます。
- TypeScript
- Python
// Backend: define an MCP server with a tool
@mcpServer({
name: 'weather',
id: 'weather',
description: 'Provides weather data',
version: '1.0.0',
})
export class WeatherMcpService extends SquidService {
@mcpTool({
description: 'Returns the current weather for a city',
inputSchema: {
type: 'object',
properties: {
city: { type: 'string', description: 'City name' },
},
required: ['city'],
},
})
async getWeather({ city }: { city: string }): Promise<string> {
return `The weather in ${city} is sunny, 25°C.`;
}
}
# Backend: define an MCP server with a tool
@mcp_server({
'name': 'weather',
'id': 'weather',
'description': 'Provides weather data',
'version': '1.0.0',
})
class WeatherMcpService(SquidService):
@mcp_tool({
'description': 'Returns the current weather for a city',
'inputSchema': {
'type': 'object',
'properties': {
'city': {'type': 'string', 'description': 'City name'},
},
'required': ['city'],
},
})
async def get_weather(self, args: dict) -> str:
return f"The weather in {args['city']} is sunny, 25°C."
これで、MCP 対応の任意の AI エージェントが、標準プロトコルを介して天気ツールを検出し、呼び出せます。
概要
MCP(Model Context Protocol) は、AI エージェントが外部サーバー上のツールを検出し、呼び出す方法を標準化するオープンプロトコルです。Squid は、バックエンドで MCP サーバーを作成するための組み込みサポートを提供します。ツールをデコレーター付きメソッドとして定義することで、エージェントが JSON-RPC を介して呼び出せるようになります。
MCP を使用する場面
| ユースケース | 推奨 |
|---|---|
| バックエンドのツールを任意の MCP 対応エージェントに公開する | MCP サーバー |
| Squid エージェント全体を MCP クライアントに公開する | エージェントを MCP サーバーとして公開するを参照 |
| エージェントが会話中にカスタムのサーバー側ロジックを必要とする | AI functions を使用 |
| エージェントが外部 MCP サーバー上のツールを呼び出す必要がある | MCP connector を使用 |
| エージェントが接続されたサービス(CRM、API など)にアクセスする必要がある | 接続済み integration を使用 |
仕組み
SquidServiceを継承するサービス内のクラスに@mcpServerデコレーターを付けます- そのクラス内のメソッドに
@mcpToolを使用して、サーバーにツールを追加します - Squid はデプロイ時に MCP サーバーを登録し、JSON-RPC エンドポイントとして公開します
- MCP 対応クライアントが接続し、
tools/listで利用可能なツールを検出し、tools/callで呼び出します - 必要に応じて、OAuth を有効にするか、
@mcpAuthorizerメソッドを追加してアクセスを制御します
クイックスタート
前提条件
- TypeScript
- Python
ステップ 1:ツールを備えた MCP サーバーを作成する
SquidService を継承するサービスクラスを作成し、@mcpServer デコレーターを付けて、ツールを追加します。
- TypeScript
- Python
import { mcpServer, mcpTool, SquidService } from '@squidcloud/backend';
@mcpServer({
name: 'greetingServer',
id: 'greetingServer',
description: 'A simple MCP server that greets users',
version: '1.0.0',
})
export class McpService extends SquidService {
@mcpTool({
description: 'Returns a greeting for the given name',
inputSchema: {
type: 'object',
properties: {
name: { type: 'string', description: 'The name to greet' },
},
required: ['name'],
},
})
async greet({ name }: { name: string }): Promise<string> {
return `Hello, ${name}!`;
}
}
from squidcloud_backend import SquidService, mcp_server, mcp_tool
@mcp_server({
'name': 'greetingServer',
'id': 'greetingServer',
'description': 'A simple MCP server that greets users',
'version': '1.0.0',
})
class McpService(SquidService):
@mcp_tool({
'description': 'Returns a greeting for the given name',
'inputSchema': {
'type': 'object',
'properties': {
'name': {'type': 'string', 'description': 'The name to greet'},
},
'required': ['name'],
},
})
async def greet(self, args: dict) -> str:
return f"Hello, {args['name']}!"
Python のツールメソッドは、TypeScript のような分割代入されたオブジェクトではなく、inputSchema のプロパティに一致する単一の args: dict を受け取ります。
ステップ 2:サービスを登録する
- TypeScript
- Python
サービスがサービスのインデックスファイルからエクスポートされていることを確認します。
export * from './mcp-service';
個別の登録手順は不要です。Python では、モジュールがインポートされると各 @mcp_server クラスが自動的に登録されるため、クラスを src/main.py に置くか、そこからインポートするだけで済みます。
ステップ 3:バックエンドをデプロイする
ローカル開発では、Squid CLI を使用してバックエンドをローカルで実行します。
squid start
クラウドへのデプロイについては、バックエンドのデプロイを参照してください。
ステップ 4:MCP サーバーをエージェントに接続する
デプロイ後、MCP サーバーを connector として追加し、エージェントの abilities に追加します。
- Squid Console で MCP connector を追加し、デプロイした MCP サーバーを接続先に指定します
- Agent Studio で connector をエージェントの abilities に追加します
これで、エージェントは会話中に MCP ツールを検出し、呼び出せます。
基本概念
@mcpServer デコレーター
@mcpServer デコレーターは、SquidService クラスを MCP サーバーとして指定します。次のフィールドを持つ設定オブジェクトを受け取ります。
| フィールド | 型 | 必須 | 説明 |
|---|---|---|---|
id | string | はい | MCP エンドポイント URL で使用される一意の識別子 |
name | string | はい | MCP マニフェストで公開されるサーバー名 |
description | string | はい | サーバーの目的を説明 |
version | string | はい | MCP マニフェストで公開されるサーバーのバージョン |
oauth | McpOAuthOptions | いいえ | すべてのリクエストに OAuth 2.0 bearer token を要求。OAuth 認証を参照 |
各 id は、アプリケーション内のすべての MCP サーバー間で一意である必要があります。ID が重複するとデプロイエラーが発生します。
- TypeScript
- Python
import { mcpServer, SquidService } from '@squidcloud/backend';
@mcpServer({
id: 'inventory',
name: 'inventoryServer',
description: 'Provides product inventory lookup and management tools',
version: '1.0.0',
})
export class InventoryMcpService extends SquidService {
// Tools go here
}
from squidcloud_backend import SquidService, mcp_server
@mcp_server({
'id': 'inventory',
'name': 'inventoryServer',
'description': 'Provides product inventory lookup and management tools',
'version': '1.0.0',
})
class InventoryMcpService(SquidService):
pass # Tools go here
@mcpTool デコレーター
@mcpTool デコレーターは、MCP クライアントが検出して呼び出せるツールとしてメソッドを公開します。次のフィールドを持つ設定オブジェクトを受け取ります。
| フィールド | 型 | 必須 | 説明 |
|---|---|---|---|
description | string | はい | ツールの機能と呼び出すタイミングをエージェントに伝える |
inputSchema | JSONSchema | はい | ツールの入力パラメーターを定義する JSON Schema |
outputSchema | JSONSchema | いいえ | ツールの出力形式を記述する JSON Schema |
メソッド名が MCP マニフェスト内のツール名になります。各ツール名はサーバー内で一意である必要があります。
- TypeScript
- Python
@mcpTool({
description: 'Looks up the current stock level for a product by SKU',
inputSchema: {
type: 'object',
properties: {
sku: {
type: 'string',
description: 'The product SKU code',
},
},
required: ['sku'],
},
})
async getStockLevel({ sku }: { sku: string }): Promise<number> {
// Look up the product using your own data layer.
const product = await this.findProduct(sku);
if (!product) {
throw new Error(`Product with SKU ${sku} not found`);
}
return product.stockLevel;
}
@mcp_tool({
'description': 'Looks up the current stock level for a product by SKU',
'inputSchema': {
'type': 'object',
'properties': {
'sku': {
'type': 'string',
'description': 'The product SKU code',
},
},
'required': ['sku'],
},
})
async def get_stock_level(self, args: dict) -> int:
sku = args['sku']
# Look up the product using your own data layer.
product = await self.find_product(sku)
if product is None:
raise RuntimeError(f"Product with SKU {sku} not found")
return product['stockLevel']
入力スキーマ
inputSchema は JSON Schema 形式に従います。TypeScript では、ツールメソッドはプロパティがスキーマに一致する単一の分割代入されたオブジェクトを受け取ります。Python では、メソッドは単一の args: dict を受け取り、各プロパティをキーで読み取ります。
- TypeScript
- Python
@mcpTool({
description: 'Searches products by category and price range',
inputSchema: {
type: 'object',
properties: {
category: {
type: 'string',
description: 'Product category to search',
enum: ['electronics', 'clothing', 'home', 'sports'],
},
maxPrice: {
type: 'number',
description: 'Maximum price in USD',
},
inStockOnly: {
type: 'boolean',
description: 'If true, only return items currently in stock',
},
},
required: ['category'],
},
})
async searchProducts({
category,
maxPrice,
inStockOnly,
}: {
category: string;
maxPrice?: number;
inStockOnly?: boolean;
}): Promise<string> {
// Query logic here
return JSON.stringify(results);
}
@mcp_tool({
'description': 'Searches products by category and price range',
'inputSchema': {
'type': 'object',
'properties': {
'category': {
'type': 'string',
'description': 'Product category to search',
'enum': ['electronics', 'clothing', 'home', 'sports'],
},
'maxPrice': {
'type': 'number',
'description': 'Maximum price in USD',
},
'inStockOnly': {
'type': 'boolean',
'description': 'If true, only return items currently in stock',
},
},
'required': ['category'],
},
})
async def search_products(self, args: dict) -> str:
category = args['category']
max_price = args.get('maxPrice')
in_stock_only = args.get('inStockOnly')
# Query logic here
return json.dumps(results)
出力スキーマ
オプションの outputSchema はツールの戻り値の構造を記述し、クライアントがレスポンス形式を理解するのに役立ちます。
- TypeScript
- Python
@mcpTool({
description: 'Returns product details for a given SKU',
inputSchema: {
type: 'object',
properties: {
sku: { type: 'string', description: 'Product SKU' },
},
required: ['sku'],
},
outputSchema: {
type: 'object',
properties: {
name: { type: 'string' },
price: { type: 'number' },
inStock: { type: 'boolean' },
},
},
})
async getProduct({ sku }: { sku: string }) {
return { name: 'Widget', price: 9.99, inStock: true };
}
@mcp_tool({
'description': 'Returns product details for a given SKU',
'inputSchema': {
'type': 'object',
'properties': {
'sku': {'type': 'string', 'description': 'Product SKU'},
},
'required': ['sku'],
},
'outputSchema': {
'type': 'object',
'properties': {
'name': {'type': 'string'},
'price': {'type': 'number'},
'inStock': {'type': 'boolean'},
},
},
})
async def get_product(self, args: dict) -> dict:
return {'name': 'Widget', 'price': 9.99, 'inStock': True}
@mcpAuthorizer デコレーター
@mcpAuthorizer デコレーターは、MCP サーバーへの各リクエストの前に実行されるメソッドを指定します。受信リクエストを検証し、認可されていない呼び出し元を拒否するために使用します。
authorizer メソッドは McpAuthorizationRequest オブジェクトを受け取り、boolean(または Promise<boolean>)を返す必要があります。リクエストを許可するには true を返し、"Unauthorized" エラーで拒否するには false を返します。
- TypeScript
- Python
import { mcpAuthorizer, McpAuthorizationRequest, mcpServer, mcpTool, SquidService } from '@squidcloud/backend';
@mcpServer({
name: 'secureMcp',
id: 'secureMcp',
description: 'An MCP server with authorization',
version: '1.0.0',
})
export class SecureMcpService extends SquidService {
@mcpAuthorizer()
async authorize(request: McpAuthorizationRequest): Promise<boolean> {
const token = request.headers['authorization'];
return token === `Bearer ${this.secrets['MCP_AUTH_TOKEN']}`;
}
@mcpTool({
description: 'Returns sensitive data',
inputSchema: {
type: 'object',
properties: {
query: { type: 'string', description: 'The data query' },
},
required: ['query'],
},
})
async getSensitiveData({ query }: { query: string }): Promise<string> {
// This tool is only accessible if the authorizer returns true
return `Results for: ${query}`;
}
}
from squidcloud_backend import (
McpAuthorizationRequest,
SquidService,
mcp_authorizer,
mcp_server,
mcp_tool,
)
@mcp_server({
'name': 'secureMcp',
'id': 'secureMcp',
'description': 'An MCP server with authorization',
'version': '1.0.0',
})
class SecureMcpService(SquidService):
@mcp_authorizer()
async def authorize(self, request: McpAuthorizationRequest) -> bool:
headers = request.get('headers') or {}
token = headers.get('authorization')
return token == f"Bearer {self.secrets['MCP_AUTH_TOKEN']}"
@mcp_tool({
'description': 'Returns sensitive data',
'inputSchema': {
'type': 'object',
'properties': {
'query': {'type': 'string', 'description': 'The data query'},
},
'required': ['query'],
},
})
async def get_sensitive_data(self, args: dict) -> str:
# This tool is only accessible if the authorizer returns True
return f"Results for: {args['query']}"
McpAuthorizationRequest のフィールド
| フィールド | 型 | 説明 |
|---|---|---|
body | any | パース済みの JSON-RPC リクエスト本文 |
queryParams | Record<string, string> | リクエスト URL のクエリパラメーター |
headers | Record<string, string> | リクエストの HTTP ヘッダー |
auth | McpAuthContext | undefined | 検証済みの認証コンテキスト。OAuth 検証に成功したリクエストにのみ存在 |
@mcpAuthorizer メソッドが定義されておらず、OAuth も有効になっていない場合、MCP サーバーへのすべてのリクエストが許可されます。
OAuth 認証
Claude やその他の MCP 対応アシスタントなど、エンドユーザーが使用する MCP クライアントでは、共有シークレットトークンは実用的ではありません。各ユーザーが自身の ID でサインインする必要があるためです。@mcpServer に oauth オプションを追加すると、すべてのリクエストに有効な OAuth 2.0 bearer token が要求されます。
import { mcpServer, mcpTool, SquidService } from '@squidcloud/backend';
@mcpServer({
id: 'crm',
name: 'crmServer',
description: 'Provides CRM lookup tools',
version: '1.0.0',
oauth: {
integrationId: 'my-auth0',
},
})
export class CrmMcpService extends SquidService {
// Tools go here
}
McpOAuthOptions にはフィールドが 1 つあります。
| フィールド | 型 | 必須 | 説明 |
|---|---|---|---|
integrationId | string | はい | このアプリに登録された認証 integration の ID |
MCP OAuth は Auth0 および Microsoft Entra ID の認証 integration をサポートしており、TypeScript Backend SDK でのみ利用できます。Python の @mcp_server デコレーターは oauth オプションを受け付けません。
oauth が設定されると、Squid は OAuth フローのリソースサーバー側を自動的に処理します。
- 有効な bearer token がないリクエストには、サーバーの保護されたリソースメタデータを指す
WWW-Authenticateチャレンジを含む HTTP401 Unauthorizedレスポンスが返されます。 - Squid は
<mcp-server-url>/.well-known/oauth-protected-resourceで OAuth 2.0 Protected Resource Metadata ドキュメントを公開し、テナントを認可サーバーとして記載します。MCP クライアントはこれを検出し、ユーザーをログインへ自動的に案内します。 - Squid は各リクエストの bearer token を参照先の integration に照らして検証します。トークンはテナントによって RS256 で署名されており(その JWKS を介して検証)、発行者がテナント、オーディエンスが integration のクライアント ID である必要があります。
Auth0 integration では、要求されるスコープは openid、profile、email、offline_access です。Entra integration では、要求されるスコープは <clientId>/.default で、トークンは v2.0 トークンである必要があり(アプリ登録で requestedAccessTokenVersion: 2)、各 MCP クライアントを事前にテナントに登録する必要があります。
oauth が有効で @mcpAuthorizer がない場合、integration の有効なトークンを持つすべてのリクエストが許可されます。
OAuth と authorizer を組み合わせる
特定のユーザーやドメインへのアクセス制限など、トークン検証に加えて独自のルールを適用するには、@mcpAuthorizer を追加します。authorizer は OAuth 検証の成功後に実行され、検証済みコンテキストは request.auth で利用できます。
import { mcpAuthorizer, McpAuthorizationRequest, mcpServer, mcpTool, SquidService } from '@squidcloud/backend';
@mcpServer({
id: 'crm',
name: 'crmServer',
description: 'Provides CRM lookup tools',
version: '1.0.0',
oauth: {
integrationId: 'my-auth0',
},
})
export class CrmMcpService extends SquidService {
@mcpAuthorizer()
async authorize(request: McpAuthorizationRequest): Promise<boolean> {
const email = request.auth?.claims['email'] as string | undefined;
return !!email && email.endsWith('@my-company.com');
}
// Tools go here
}
McpAuthContext のフィールド:
| フィールド | 型 | 説明 |
|---|---|---|
type | 'oauth' | このコンテキストを生成した認証メカニズム |
integrationId | string | リクエストの検証に使用された認証 integration の ID |
claims | Record<string, unknown> | 検証済みの JWT claims(sub、aud、iss、exp、カスタム claims) |
検証済み claims は @mcpAuthorizer 内でのみ利用できます。@mcpTool メソッドが受け取るのは入力引数のみです。ツール内でユーザーごとのコンテキストを期待するのではなく、authorizer で ID ベースのアクセス制御を一元的に適用してください。
エラー処理
ツールエラー
ツールメソッドがエラーをスローすると、MCP サーバーはそれをキャッチし、isError: true を含むツールレスポンスとして返します。呼び出し元のエージェントはエラーメッセージを受け取り、それを伝えるか、次の対応を判断できます。
エージェントが有用なフィードバックを提供できるよう、明確で具体的なエラーをスローしてください。
- TypeScript
- Python
@mcpTool({
description: 'Cancels an order by ID',
inputSchema: {
type: 'object',
properties: {
orderId: { type: 'string', description: 'The order ID to cancel' },
},
required: ['orderId'],
},
})
async cancelOrder({ orderId }: { orderId: string }): Promise<string> {
// Look up the order using your own data layer.
const order = await this.findOrder(orderId);
if (!order) {
throw new Error(`Order ${orderId} not found`);
}
if (order.status === 'shipped') {
throw new Error(`Order ${orderId} has already shipped and cannot be cancelled`);
}
await this.updateOrderStatus(orderId, 'cancelled');
return `Order ${orderId} has been cancelled`;
}
@mcp_tool({
'description': 'Cancels an order by ID',
'inputSchema': {
'type': 'object',
'properties': {
'orderId': {'type': 'string', 'description': 'The order ID to cancel'},
},
'required': ['orderId'],
},
})
async def cancel_order(self, args: dict) -> str:
order_id = args['orderId']
# Look up the order using your own data layer.
order = await self.find_order(order_id)
if order is None:
raise RuntimeError(f"Order {order_id} not found")
if order['status'] == 'shipped':
raise RuntimeError(f"Order {order_id} has already shipped and cannot be cancelled")
await self.update_order_status(order_id, 'cancelled')
return f"Order {order_id} has been cancelled"
プロトコルレベルのエラー
MCP サーバーは、プロトコルレベルの問題に標準の JSON-RPC エラーコードを使用します。
| エラーコード | 意味 | 原因 |
|---|---|---|
-32001 | Unauthorized | @mcpAuthorizer メソッドが false を返した |
-32601 | Method not found | 要求された JSON-RPC メソッドまたはツール名が存在しない |
-32000 | Server error | MCP サーバー ID が見つからなかった、または内部エラーが発生した |
OAuth が有効な場合、bearer token がない、または無効なリクエストは、JSON-RPC 処理の前に WWW-Authenticate チャレンジを含む HTTP 401 Unauthorized レスポンスで拒否されます。
よくある問題
| 問題 | 原因 | 解決策 |
|---|---|---|
| ID の重複エラーでデプロイが失敗する | 2 つの @mcpServer クラスが同じ id を使用している | MCP サーバーごとに一意の id を使用する |
| ツール名の重複でデプロイが失敗する | 同じサーバー内の 2 つの @mcpTool メソッドが同じ名前を持つ | いずれかのメソッドの名前を変更する |
| エージェントがツールを呼び出さない | ツールの説明がユーザーのプロンプトと一致していない | ツールの機能を明確に示すよう説明を書き直す |
| 認可が常に失敗する | トークンまたはヘッダーのチェックが正しくない | デバッグのために McpAuthorizationRequest のフィールドをログに記録する |
OAuth がすべてのリクエストで 401 invalid_token を返す | トークンの発行者またはオーディエンスが integration と一致しない | トークンが integration のテナントから発行されたことを確認する。オーディエンスは integration のクライアント ID である必要がある。Entra トークンは v2.0 トークンである必要がある |
| OAuth が有効なサーバーがすべてのリクエストを拒否する | oauth.integrationId がサポートされている認証 integration を参照していない | アプリに Auth0 または Entra ID integration を登録し、その ID を使用する |
ベストプラクティス
明確なツールの説明を書く
description は、エージェントがツールを呼び出すタイミングを判断する主な手段です。ツールの機能と返す情報を具体的に記述してください。
Good: 'Returns the current stock level for a product. Use when asked about inventory or availability.'
Bad: 'Gets product info'
入力スキーマを慎重に設計する
- ツールがパラメーターなしでは機能しない場合にのみ、そのパラメーターを
requiredに指定する enumを使用して、値を既知の選択肢に制限する- エージェントが指定すべき形式を把握できるよう、各プロパティに明確な
descriptionフィールドを記述する - 適切な JSON Schema 型(
string、number、boolean、array、object)を使用する
MCP サーバーを保護する
- サーバーが機密性の高い操作を公開する場合は、必ず
@mcpAuthorizerを追加する - 認可トークンはハードコードされた値ではなく、保存されたシークレットと照合して検証する
- 認証(誰が呼び出しているか)と認可(何ができるか)の両方を確認する
- Claude などのユーザー向け MCP クライアントでは、共有トークンよりも OAuth 認証を優先し、authorizer 内で
request.auth?.claimsを使用してユーザーごとのルールを適用する
ツールの入力を検証する
入力スキーマには型の制約がありますが、エッジケースに対応するため、ツールメソッド内でも入力を検証してください。
- TypeScript
- Python
@mcpTool({
description: 'Transfers funds between accounts',
inputSchema: {
type: 'object',
properties: {
fromAccount: { type: 'string', description: 'Source account ID' },
toAccount: { type: 'string', description: 'Destination account ID' },
amount: { type: 'number', description: 'Amount to transfer in USD' },
},
required: ['fromAccount', 'toAccount', 'amount'],
},
})
async transferFunds({
fromAccount,
toAccount,
amount,
}: {
fromAccount: string;
toAccount: string;
amount: number;
}): Promise<string> {
if (amount <= 0) {
throw new Error('Transfer amount must be positive');
}
if (fromAccount === toAccount) {
throw new Error('Source and destination accounts must be different');
}
// Process transfer...
return `Transferred $${amount} from ${fromAccount} to ${toAccount}`;
}
@mcp_tool({
'description': 'Transfers funds between accounts',
'inputSchema': {
'type': 'object',
'properties': {
'fromAccount': {'type': 'string', 'description': 'Source account ID'},
'toAccount': {'type': 'string', 'description': 'Destination account ID'},
'amount': {'type': 'number', 'description': 'Amount to transfer in USD'},
},
'required': ['fromAccount', 'toAccount', 'amount'],
},
})
async def transfer_funds(self, args: dict) -> str:
from_account = args['fromAccount']
to_account = args['toAccount']
amount = args['amount']
if amount <= 0:
raise RuntimeError('Transfer amount must be positive')
if from_account == to_account:
raise RuntimeError('Source and destination accounts must be different')
# Process transfer...
return f"Transferred ${amount} from {from_account} to {to_account}"
ツールの役割を絞る
各ツールは 1 つのことを適切に行うようにします。多くの操作を処理する単一のツールよりも、小さく役割を絞った複数のツールを優先してください。これにより、エージェントがタスクに適したツールを選択しやすくなります。
エージェントを MCP サーバーとして公開する
ここまでは、_独自の_バックエンドツールから MCP サーバーを構築する方法を説明しました。逆の方法も利用できます。任意の Squid エージェント自体を、バックエンドコードなしで MCP サーバーとして公開できます。このサーバーは、プロンプトをエージェントに転送する単一の ask ツールを公開します。これにより、IDE アシスタントなどの MCP クライアントは、指示、connector、ナレッジベースがすでに設定されたエージェントに問い合わせることができます。
エンドポイントは標準の MCP Streamable HTTP トランスポートを介して /mcp/<agentId> で提供されます。
ask ツールはデフォルトで最大 10 分間実行されます。呼び出し元はオプションの timeoutMs ツール引数を指定できます(1 ミリ秒から 1 時間まで。無効な値の場合は JSON-RPC エラー -32602 が返されます)。上限はエージェント自体に設定された timeoutMs です。MCP の呼び出し元が切断すると、実行は停止します。
設定には API キーが必要なため、バックエンドコードから実行してください。
const agent = this.squid.ai().agent('banking-copilot');
// Let Squid draft the descriptions from the agent's instructions and connected resources.
// This returns them without saving, so you can review or edit them first.
const generated = await agent.generateMcpDescriptions();
await agent.updateMcpServer({
enabled: true,
description: generated.description,
toolDescription: generated.toolDescription,
requireApiKey: true,
});
設定オプション
| フィールド | 説明 |
|---|---|
enabled | エージェントを MCP サーバーとして公開するかどうか |
description | MCP の initialize 結果の instructions フィールドとして提供される。デフォルトはエージェントの説明 |
toolDescription | ツールマニフェスト内の ask ツールの説明。デフォルトは汎用的な説明 |
oauthIntegrationId | 認証 connector の bearer token を使用してエンドポイントを OAuth で保護する |
requireApiKey | エージェント自身の API キーを bearer token として要求する |
エンドポイントを保護する
oauthIntegrationId と requireApiKey のどちらも設定されていない場合、MCP エンドポイントは公開状態になります。エージェント ID を知っている人なら誰でも呼び出すことができ、呼び出しのたびに AI クォータが消費されます。意図的にエージェントを公開する場合を除き、必ず少なくとも一方を設定してください。
requireApiKey を使用する場合、呼び出し元は Authorization: Bearer <key> または x-squid-agent-api-key ヘッダーでエージェントの API キーを提示します。これはアプリケーションの API キーではなく、エージェントを対象とするキーであるため、そのエージェントへのアクセスのみが許可されます。バックエンドコードからキーを取得またはローテーションできます。
const agent = this.squid.ai().agent('banking-copilot');
const key = await agent.getApiKey();
const rotated = await agent.regenerateApiKey();
oauthIntegrationId と requireApiKey の両方を設定すると、いずれかの認証情報が受け入れられます。これにより、対話型クライアントは OAuth でサインインし、自動化されたクライアントはエージェントキーを提示できます。
oauthIntegrationId を使用する場合、検証済み bearer token の ID がリクエストのユーザーになります。ナレッジベースのアクセススコープと AI functions はその ID を参照でき、エージェントの auditLog が有効な場合、エントリには userName タグが付き、認可された各リクエストと拒否された認証情報について mcp_auth エントリが記録されます。エージェントの監査ログを参照してください。
次のステップ
- MCP connectors - Squid Console を介してエージェントを MCP サーバーに接続する
- Auth0 認証 - MCP OAuth に使用する Auth0 integration を設定する
- Abilities - MCP connector やその他のツールをエージェントに追加する
- AI functions - バックエンドロジックをエージェントに公開する別の方法
- AI エージェントのドキュメント - AI エージェントを構築し、設定する