自前でMCP serverを作成したかったが、使うまでの設定をどうやるのかわからなかったのでメモ
ちょうどcopilot agentにMCP serverを設定できる機能がvscodeに来たのでやってみた
MCP(model context protocol)はclaudeで有名な、Anthropicが考案したプロトコル。AIモデル(LLM)が使用する、ツールやリソース(サービスやデータ)をやり取りするためのプロトコル。が、copilotが対応したことからもわかるように、おそらくAIモデルの機能を拡張する際の標準プロトコルになりつつある
環境
- vscode: 1.99
- node: ^18.0.0
- “@modelcontextprotocol/sdk”: ^1.8.0
- typescript: ^4.5.0
実装
MCP serverの実装。動作確認のためなので、簡単なものを。dice rollの例を見つけたので真似てやってみる というかほぼcopilot agentに書かせた。検索を有効化していたので、URLみせると参照してそれっぽく書いてくれて便利
# src/app.ts
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { Tool } from "@modelcontextprotocol/sdk/types.js";
export interface DiceRoll {
faces: number;
}
// Define the dice roll tool
const rollDiceTool: Tool = {
name: "roll-dice",
description: "Roll a dice with a specified number of faces.",
inputSchema: {
type: "object",
properties: {
faces: {
type: "integer",
minimum: 1,
default: 6,
},
},
},
async handler({ faces }: DiceRoll) {
const result = Math.floor(Math.random() * faces) + 1;
return {
content: [
{
type: "text",
text: `Rolled a ${faces}-sided dice: ${result}`,
},
],
};
},
};
// Register the tool and start the server
const server = new McpServer({
name: "DiceRollServer",
version: "1.0.0",
tools: [rollDiceTool],
});
const transport = new StdioServerTransport();
await server.connect(transport);
console.log("MCP Server is running and ready to accept requests.");
modelcontextprotocol/sdkの使い方は発展途上らしく、serverの書き方が色々ありすぎて難しい。シンプルにやるなら、toolに全部書くと楽なのだろうか
設定
vscodeに設定
特定のワークスペース内で設定したい場合は
.vscode/mcp.json
全体に適用したい場合はユーザーの設定ファイル
~/.config/Code/User/settings.json
{
"inputs": [],
"servers": {
"mcp-server-diceroll": {
"command": "npx",
"args": ["-y", "mcp-server-diceroll"],
"env": {}
}
}
}
呼び出し
vscodeから呼び出す。MCP serverをinstall、起動する
copilot chatの画面からagentを選択するとツールアイコンが表示されるのでinstallや有効化をする。各MCP serverのon/offの切り替えもできる
実行結果。基本、コードをかく役割を持っているからか、ツール名を指定しないと使ってくれなかった