TypeScriptでMCPサーバーを自作し、ローカルで動かして呼び出すまでの手順です。公式のTypeScript SDKのv2を使い、MCP InspectorのCLIと、SDKのクライアントの2つから実際に呼び出しました。動かしている途中で気づいた注意点も、後半にまとめています。
TypeScript SDKは2026年7月にv2が出て、パッケージが @modelcontextprotocol/sdk(v1)から @modelcontextprotocol/server と @modelcontextprotocol/client に分かれました(SDKのリポジトリのREADME)。v1の書き方の記事をそのまま試すと動かないので、注意してください(後述)。
結論
| やりたいこと | コマンド |
|---|---|
| SDKを入れる | npm install @modelcontextprotocol/server@2.4.0 @modelcontextprotocol/client@2.4.0 zod@4.6.7 |
| サーバーを動かす | node src/server.ts |
| ツールの一覧を見る | npx -y @modelcontextprotocol/inspector@2.14.0 --cli node src/server.ts --method tools/list |
| ツールを呼ぶ | npx -y @modelcontextprotocol/inspector@2.14.0 --cli node src/server.ts --method tools/call --tool-name count_chars --tool-arg text=こんにちは👋 |
| クライアントから呼ぶ | node src/client.ts |
- Node.js 22.18.0以降は、TypeScriptのファイルを
nodeで直接実行できます(Node.jsの公式ドキュメント)。この記事では、ビルドもtsxも使わずに動かしています。 - サーバーのログは
console.error(標準エラー出力)に出します。標準出力はMCPの通信に使います。
動作確認した環境
- Node.js 26.13.0(Dockerイメージ
node:26.13.0-trixie-slim。2026年11月5日時点のLTS)、npm 11.20.0 @modelcontextprotocol/server2.4.0、@modelcontextprotocol/client2.4.0、zod4.6.7@modelcontextprotocol/inspector2.14.0- Docker 29.7.2(Windows 11 の Docker Desktop。Linuxコンテナの設定)
- 確認日: 2026年11月5日
この記事は、MacとWindowsの両方の読者を対象にしています。手順はDockerのコンテナ(Linux)の中で実行するので、MacでもWindowsでもDockerがあれば同じ手順で試せる想定です。確認はWindows 11 のDocker Desktopで行い、Macでは確認していません。OSで違うのは、最後の「アプリに登録する」の設定ファイルの場所などです。
この記事のコマンドは、Claude(AI)が1つのコンテナで上から順に実行して確認しました。最後の「アプリに登録する」の章は、公式ドキュメントに基づく内容で、実際のアプリには登録していません。
準備
Node.jsのコンテナを起動し、プロジェクトを作ります。SDKのチュートリアルに従い、package.json の type を module にします(ないときの動きは後述)。
$ docker run --rm -it --name mcp-demo node:26.13.0-trixie-slim bash
$ mkdir -p ~/demo/src && cd ~/demo
$ node -v; npm -v
v26.13.0
11.20.0
$ npm init -y > /dev/null && npm pkg set type=module
$ npm install @modelcontextprotocol/server@2.4.0 @modelcontextprotocol/client@2.4.0 zod@4.6.7
added 14 packages, and audited 15 packages in 3s
2 packages are looking for funding
run `npm fund` for details
found 0 vulnerabilities
この記事の .ts のファイルは、自分のPCで作ってから docker cp でコンテナに入れます。コンテナに入ったターミナルとは別に、PCのターミナル(MacのターミナルやWindowsのPowerShell)を開き、ファイルを保存したフォルダで実行します。
docker cp server.ts mcp-demo:/root/demo/src/server.ts
確認では、名前の違うコンテナ(mcpts-run)をバックグラウンドで起動し、docker exec でコマンドを送り、ファイルは同じように docker cp で入れました。docker cp はWindows 11 のGit Bashから実行し、MacとPowerShellからは実行していません。以降のプロンプトは $ で表しています。
サーバーを書く
ツールを2つ持つサーバーです。count_chars は文字数を数え、divide は割り算をします。PCで server.ts として保存し、上の docker cp でコンテナの src/server.ts に入れます。
import { McpServer } from '@modelcontextprotocol/server';
import { serveStdio } from '@modelcontextprotocol/server/stdio';
import * as z from 'zod/v4';
function createServer(): McpServer {
const server = new McpServer({ name: 'demo-tools', version: '1.0.0' });
server.registerTool(
'count_chars',
{
description: '文字列の文字数を数える',
inputSchema: z.object({ text: z.string().min(1).describe('数える文字列') })
},
async ({ text }) => {
return { content: [{ type: 'text', text: `文字数: ${[...text].length}(UTF-16の長さ: ${text.length})` }] };
}
);
server.registerTool(
'divide',
{
description: 'a を b で割る',
inputSchema: z.object({ a: z.number(), b: z.number() })
},
async ({ a, b }) => {
if (b === 0) {
return { content: [{ type: 'text', text: '0では割れません' }], isError: true };
}
return { content: [{ type: 'text', text: String(a / b) }] };
}
);
return server;
}
void serveStdio(createServer);
console.error('demo-tools MCP server running on stdio');
registerToolに、ツール名、説明と入力のスキーマ、処理を渡します。入力のスキーマはZodで書き、SDKがJSON Schemaに変換してクライアントに伝えます。- 失敗を返すときは、結果に
isError: trueをつけます。 serveStdioは、標準入力からリクエストを読み、標準出力に応答を書きます。
起動する
node で直接実行します。起動の表示は標準エラー出力に出ます。確認では標準入力を閉じた状態(< /dev/null)で実行したので、表示のあとすぐに終了しました。標準入力を閉じずに実行すると、クライアントからの入力を待ち続けます(SDKのチュートリアル)。
$ node src/server.ts < /dev/null
demo-tools MCP server running on stdio
Inspector のCLIで呼ぶ
MCP Inspectorには、ブラウザの画面のほかにCLIがあります。--cli のあとにサーバーを起動するコマンドを書くと、Inspectorがサーバーを起動して呼び出します。ツールの一覧です。Zodのスキーマが、JSON Schemaになっていることが分かります。
$ npx -y @modelcontextprotocol/inspector@2.14.0 --cli node src/server.ts --method tools/list
demo-tools MCP server running on stdio
{
"tools": [
{
"name": "count_chars",
"description": "文字列の文字数を数える",
"inputSchema": {
"type": "object",
"properties": {
"text": {
"type": "string",
"minLength": 1,
"description": "数える文字列"
}
},
"required": [
"text"
],
"$schema": "https://json-schema.org/draft/2020-12/schema"
}
},
{
"name": "divide",
"description": "a を b で割る",
"inputSchema": {
"type": "object",
"properties": {
"a": {
"type": "number"
},
"b": {
"type": "number"
}
},
"required": [
"a",
"b"
],
"$schema": "https://json-schema.org/draft/2020-12/schema"
}
}
]
}
ツールを呼びます。絵文字の「👋」は1文字ですが、JavaScriptの length(UTF-16の長さ)では2と数えられます。
$ npx -y @modelcontextprotocol/inspector@2.14.0 --cli node src/server.ts --method tools/call --tool-name count_chars --tool-arg text=こんにちは👋
demo-tools MCP server running on stdio
{
"content": [
{
"type": "text",
"text": "文字数: 6(UTF-16の長さ: 7)"
}
]
}
ツールが isError: true を返したときと、存在しないツールを呼んだときは、終了コードが5になりました。
$ npx -y @modelcontextprotocol/inspector@2.14.0 --cli node src/server.ts --method tools/call --tool-name divide --tool-arg a=1 --tool-arg b=0
demo-tools MCP server running on stdio
{
"content": [
{
"type": "text",
"text": "0では割れません"
}
],
"isError": true
}
{"error":{"code":"tool_is_error","message":"Tool 'divide' returned isError:true."}}
$ npx -y @modelcontextprotocol/inspector@2.14.0 --cli node src/server.ts --method tools/call --tool-name nope
demo-tools MCP server running on stdio
{"error":{"code":"tool_not_found","message":"Tool 'nope' not found on server."}}
終了コードは、検証用のスクリプトで記録しました。CIなどで使うときは、この終了コードで失敗を判定できます。
クライアントを書いて呼ぶ
SDKのクライアントで、同じサーバーを呼びます。クライアントがサーバーを子プロセスとして起動するので、サーバーを先に起動しておく必要はありません。PCで client.ts として保存し、docker cp client.ts mcp-demo:/root/demo/src/client.ts でコンテナに入れます。
import { Client } from '@modelcontextprotocol/client';
import { StdioClientTransport } from '@modelcontextprotocol/client/stdio';
const client = new Client({ name: 'demo-client', version: '1.0.0' });
const transport = new StdioClientTransport({ command: 'node', args: ['src/server.ts'] });
client.onerror = (e) => console.error('onerror:', e.message);
const calls = [
{ name: 'count_chars', arguments: { text: 'こんにちは👋' } },
{ name: 'divide', arguments: { a: 10, b: 4 } },
{ name: 'divide', arguments: { a: 1, b: 0 } },
{ name: 'divide', arguments: { a: 1, b: '2' } },
{ name: 'nope', arguments: {} }
];
try {
await client.connect(transport);
const { tools } = await client.listTools();
console.log('tools:', tools.map((t) => t.name).join(', '));
for (const call of calls) {
try {
const result = await client.callTool(call);
const text = result.content.map((b) => (b.type === 'text' ? b.text : `[${b.type}]`)).join(' ');
console.log(`${call.name} ${JSON.stringify(call.arguments)} -> isError=${result.isError ?? false}: ${text}`);
} catch (e) {
console.log(`${call.name} ${JSON.stringify(call.arguments)} -> 例外: ${(e as Error).message}`);
}
}
} finally {
await client.close();
}
$ node src/client.ts
demo-tools MCP server running on stdio
tools: count_chars, divide
count_chars {"text":"こんにちは👋"} -> isError=false: 文字数: 6(UTF-16の長さ: 7)
divide {"a":10,"b":4} -> isError=false: 2.5
divide {"a":1,"b":0} -> isError=true: 0では割れません
divide {"a":1,"b":"2"} -> isError=true: Input validation error: Invalid arguments for tool divide: b: Invalid input: expected number, received string
nope {} -> 例外: Tool nope not found
失敗のしかたは3通りありました。
- ツールの処理が
isError: trueを返した(0で割る): 普通の結果として返ります。 - 引数がスキーマに合わない(
bが文字列): 処理が動く前にSDKが止め、isError: trueの結果として返ります。 - 存在しないツールを呼んだ:
callToolが例外を投げます。
ハマりやすい点
InspectorのCLIで通っても、クライアントでは型のエラーになることがある
上のクライアントでは、b に文字列の "2" を渡すと検証エラーになりました。ところが、InspectorのCLIに同じ引数をJSONで渡すと、エラーにならずに計算されました。今回の版のInspectorは、ツールのスキーマに合わせて値を数値に変換しているようです。
$ npx -y @modelcontextprotocol/inspector@2.14.0 --cli node src/server.ts --method tools/call --tool-name divide --tool-args-json '{"a":1,"b":"2"}'
demo-tools MCP server running on stdio
{
"content": [
{
"type": "text",
"text": "0.5"
}
]
}
InspectorのCLIのREADMEには、--tool-args-json は変換せずにそのまま渡すと書かれていますが、今回の結果はそうなりませんでした。型が合っているかを確かめたいときは、SDKのクライアントなど、値をそのまま送る方法でも試すのが確実です。
標準出力にログを出すと、クライアントによっては通信が壊れる
公式のチュートリアルは、標準出力は通信専用なので console.log を使わないよう警告しています。実際に、count_chars の処理に console.log を1行足して試しました。
$ cp src/server.ts /tmp/server.ts.bak
$ sed -i "/文字数:/i\ console.log('debug:', text);" src/server.ts && grep -n -A1 "debug" src/server.ts
15: console.log('debug:', text);
16- return { content: [{ type: 'text', text: `文字数: ${[...text].length}(UTF-16の長さ: ${text.length})` }] };
$ node src/client.ts
demo-tools MCP server running on stdio
tools: count_chars, divide
count_chars {"text":"こんにちは👋"} -> isError=false: 文字数: 6(UTF-16の長さ: 7)
divide {"a":10,"b":4} -> isError=false: 2.5
divide {"a":1,"b":0} -> isError=true: 0では割れません
divide {"a":1,"b":"2"} -> isError=true: Input validation error: Invalid arguments for tool divide: b: Invalid input: expected number, received string
nope {} -> 例外: Tool nope not found
今回のSDKのクライアントは、JSONでないログの行を何も表示せずに読み飛ばし、呼び出しは成功しました。次に、ログをJSONの形で出してみます。
$ cp /tmp/server.ts.bak src/server.ts
$ sed -i "/文字数:/i\ console.log(JSON.stringify({ debug: text }));" src/server.ts && grep -n -A1 "debug" src/server.ts
15: console.log(JSON.stringify({ debug: text }));
16- return { content: [{ type: 'text', text: `文字数: ${[...text].length}(UTF-16の長さ: ${text.length})` }] };
$ node src/client.ts
demo-tools MCP server running on stdio
tools: count_chars, divide
onerror: [
{
"code": "invalid_union",
"errors": [
[
{
"code": "invalid_value",
"values": [
"2.0"
],
"path": [
"jsonrpc"
],
"message": "Invalid input: expected \"2.0\""
},
(152行を省略)
"path": [],
"message": "Invalid input"
}
]
count_chars {"text":"こんにちは👋"} -> isError=false: 文字数: 6(UTF-16の長さ: 7)
divide {"a":10,"b":4} -> isError=false: 2.5
divide {"a":1,"b":0} -> isError=true: 0では割れません
divide {"a":1,"b":"2"} -> isError=true: Input validation error: Invalid arguments for tool divide: b: Invalid input: expected number, received string
nope {} -> 例外: Tool nope not found
$ cp /tmp/server.ts.bak src/server.ts
JSONの行は、MCPのメッセージとして読まれ、形が違うという検証エラーが onerror に出ました。今回のクライアントでは呼び出しは続きましたが、公式のチュートリアルは、標準出力にログを1行出すとホスト(Claude CodeやVS Codeなどのアプリ)が接続を切ると書いています。今回はアプリでは試していません。ログは console.error に出すのが確実です。
v1の記事の書き方では、パッケージが見つからない
v1の記事では、@modelcontextprotocol/sdk からインポートします。v2のパッケージだけを入れた環境で試すと、パッケージが見つからないエラーになりました。
$ printf '%s\n' "import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';" > src/v1.ts && node src/v1.ts
node:internal/modules/package_json_reader:343
throw new ERR_MODULE_NOT_FOUND(packageName, fileURLToPath(base), null);
^
Error [ERR_MODULE_NOT_FOUND]: Cannot find package '@modelcontextprotocol/sdk' imported from /root/demo/src/v1.ts
(以下略)
移行ガイドによると、インポート先のほかにも、.tool() が registerTool になり、入力のスキーマを z.object() で包むなどの違いがあります。移行ガイドにはコードを書き換えるツール(codemod)も紹介されています。
Node.jsで直接動かすと、enum が使えない
Node.jsは型の部分を取り除いて実行するだけなので、enum のように実行時のコードが必要な書き方はエラーになりました。Node.js 26では、これを変換して動かすフラグも削除されています(Node.jsの公式ドキュメント)。選択肢を表したいときは、z.enum() や文字列の型を使います。
$ printf '%s\n' 'enum Unit { Char, Byte }' 'console.error(Unit.Char);' > src/enum.ts && node src/enum.ts
(4行を省略)
file:///root/demo/src/enum.ts:1
enum Unit { Char, Byte }
^^^^^^^^^^^^^^^^^^^^^^^^
console.error(Unit.Char);
SyntaxError [ERR_UNSUPPORTED_TYPESCRIPT_SYNTAX]: TypeScript enum is not supported in strip-only mode
(以下略)
package.json に type がないと警告が出る
"type": "module" を消して実行すると、ESモジュールとして読み直したという警告が、クライアントとサーバーの両方から出ました。呼び出し自体は成功し、警告は標準エラー出力なので通信も壊れませんでしたが、余計な処理が入るので type は設定しておきます。
$ npm pkg delete type && node src/client.ts; npm pkg set type=module
(node:455) [MODULE_TYPELESS_PACKAGE_JSON] Warning: Module type of file:///root/demo/src/client.ts is not specified and it doesn't parse as CommonJS.
Reparsing as ES module because module syntax was detected. This incurs a performance overhead.
To eliminate this warning, add "type": "module" to /root/demo/package.json.
(Use `node --trace-warnings ...` to show where the warning was created)
(node:462) [MODULE_TYPELESS_PACKAGE_JSON] Warning: Module type of file:///root/demo/src/server.ts is not specified and it doesn't parse as CommonJS.
(3行を省略)
demo-tools MCP server running on stdio
tools: count_chars, divide
(以下、通常と同じ結果のため省略)
アプリに登録する(MacとWindows)
この章は公式ドキュメントに基づく内容で、MacとWindowsのどちらでも、実際のアプリには登録していません。
アプリはサーバーをPCの上で起動するので、ここまでコンテナの中で行った準備を、PCでも行います。PCにNode.js 22.18.0以降を入れ、プロジェクトのフォルダで「準備」と同じ npm init -y、npm pkg set type=module、npm install を実行し、src/server.ts を置きます。PCでの準備は確認していません。
Claude Code
プロジェクトのフォルダで、-- のあとにサーバーを起動するコマンドを書きます。公式ドキュメントには、MacとWindowsで分けた書き方はありません。登録後、Claude Codeのセッションで /mcp を実行すると、接続の状態が確認できます(Claude CodeとSDKの公式ドキュメント)。
claude mcp add --transport stdio demo-tools -- node src/server.ts
Claude Desktop
設定ファイルの場所がOSで違います。パスは絶対パスで書きます(MCPの公式ドキュメント)。
| OS | 設定ファイル |
|---|---|
| Mac | ~/Library/Application Support/Claude/claude_desktop_config.json |
| Windows | %APPDATA%\Claude\claude_desktop_config.json |
Macの例です。/Users/you/demo は、自分のプロジェクトの場所に置き換えます。
{
"mcpServers": {
"demo-tools": {
"command": "node",
"args": ["/Users/you/demo/src/server.ts"]
}
}
}
Windowsの例です。JSONの中では \ を \\ と書きます。
{
"mcpServers": {
"demo-tools": {
"command": "node",
"args": ["C:\\Users\\you\\demo\\src\\server.ts"]
}
}
}
設定を変えたら、Claude Desktopを完全に終了してから起動し直します(MCPの公式ドキュメント)。

コメント