# MCPについて調べてみる

- 公開日: 2025-04-11
- タグ: 生成AI
- URL: https://tminasen.dev/blog/976f8b32-937c-4cb8-b6f5-6d5e62228750

> MCP(Model Context Protocol)とは何かを調べ、MCPサーバを実際に作ってClaudeから使ってみた記事。発生した問題と動作確認の結果を含め、思ったより簡単にサーバを立てられたという感想をまとめている。

# 概要

最近Claudeとたくさんお話しして今更ながら感動している。  
色々試したくなっているので、最近良く聞くMCPについて調べる。

# 関連リンク

- [https://modelcontextprotocol.io/introduction](https://modelcontextprotocol.io/introduction)
- [tminasen/mcp\-server\-sample](https://github.com/tminasen/mcp-server-sample)

# MCPとは

> MCP is an open protocol that standardizes how applications provide context to LLMs. Think of MCP like a USB-C port for AI applications. Just as USB-C provides a standardized way to connect your devices to various peripherals and accessories, MCP provides a standardized way to connect AI models to different data sources and tools.

MCPとは↑の通り。  
ざっくり言うとMCPはUSB-Cのようなもので、アプリケーションがLLMにContextを提供するための標準化するプロトコル。  
AというアプリケーションやBというアプリケーションが提供する情報をClaudeやChatGPTが使えるようにするものということ。  

なぜ、MCPなのかというとAgentや複雑なworkflowをLLM上に構築する際に役立つから。  
LLMはデータやツールの統合を頻繁に必要とするので、MCPがその間を取り持ってくれる。

# 実際にやってみる

## MCPサーバを作ってみる

↓を参考に作っていく。  
[https://modelcontextprotocol.io/quickstart/server#node](https://modelcontextprotocol.io/quickstart/server#node)

```bash
# 適当なフォルダを作成して
-> % mkdir mcp-server-sample
-> % cd mcp-server-sample
# npm initで初期化して
-> % npm init -y
# 必要なライブラリをinstall
-> % npm install @modelcontextprotocol/sdk zod
-> % npm install -D @types/node typescript
# メインのソースコード用ファイルを追加
-> % mkdir src && touch src/index.ts
```

`package.json`と `tsconfig.json`をそれぞれ以下の通り修正。

```diff
   "version": "1.0.0",
   "main": "index.js",
   "scripts": {
+    "build": "tsc && chmod 755 build/index.js",
     "test": "echo \"Error: no test specified\" && exit 1"
   },
+  "type": "module",
+  "bin": {
+    "mcp-server-sample": "build/index.js"
+  },
+  "files": [
+    "build"
+  ],
   "keywords": [],
   "author": "",
   "license": "ISC",

```

```diff
+{
+    "compilerOptions": {
+      "target": "ES2022",
+      "module": "Node16",
+      "moduleResolution": "Node16",
+      "outDir": "./build",
+      "rootDir": "./src",
+      "strict": true,
+      "esModuleInterop": true,
+      "skipLibCheck": true,
+      "forceConsistentCasingInFileNames": true
+    },
+    "include": ["src/**/*"],
+    "exclude": ["node_modules"]
+  }
+  
```

MCPサーバとして起動できるように `src/index.ts`を修正していく。  
また合わせて内容も追加し、最終的に以下の通りとした。

```tsx
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
import { z } from "zod";

const server = new McpServer({
  name: "mcp-server-sample",
  version: "1.0.0",
  capabilities: {
    resources: {},
    tools: {},
  },
});

server.tool("get-tminasen-info", "get tminasen infomation", {}, () => {
  return {
    content: [
      {
        type: "text",
        text: "tminasen is web developer.",
      },
    ],
  };
});

server.tool(
  "get-tminasen-skills",
  "get tminasen's skill infomation",
  {
    genre: z.union([z.literal("FE"), z.literal("BE")]).describe("skill genre"),
  },
  ({ genre }) => {
    const skills =
      genre === "FE"
        ? ["React", "Angular", "Tailwind CSS"]
        : ["Express", "Spring Boot"];
    return {
      content: [
        {
          type: "text",
          text: `tminasen's ${genre} skills are ${skills.join(", ")}.`,
        },
      ],
    };
  }
);

async function main() {
    const transport = new StdioServerTransport();
    await server.connect(transport);
    console.error("Weather MCP Server running on stdio");
  }

  main().catch((error) => {
    console.error("Fatal error in main():", error);
    process.exit(1);
  });

```

最後に `npm run build`でbuildして準備完了。

## MCPサーバ使ってみる

ローカルのMCPサーバはClaude for Desktopを使えば確認できる。  
(他の方法もあるかもだが、今回はDocumentに沿ってClaude for Desktopを使う。)  

MCPサーバを使ってもらうように設定ファイル (`~/Library/Application Support/Claude/claude_desktop_config.json`)に以下の通り情報を追加する。

```json
{
    "mcpServers": {
        "mcp-server-sample": {
            "command": "node",
            "args": [
                "/ABSOLUTE/PATH/TO/PARENT/FOLDER/mcp-server-sample/build/index.js"
            ]
        }
    }
}
```

この状態でClaude for Desktopを起動すれば、MCPサーバの情報を見てくれるようになる。

### 問題発生

うまく起動しない。
`mcp.log`と `mcp-server-mcp-server-sample.log`に以下のように出力されていた。

```text
2025-04-11T12:09:05.526Z [info] [mcp-server-sample] Initializing server...
2025-04-11T12:09:05.541Z [error] [mcp-server-sample] spawn node ENOENT
2025-04-11T12:09:05.541Z [error] [mcp-server-sample] spawn node ENOENT
2025-04-11T12:09:05.543Z [info] [mcp-server-sample] Server transport closed
2025-04-11T12:09:05.543Z [info] [mcp-server-sample] Client transport closed
2025-04-11T12:09:05.543Z [info] [mcp-server-sample] Server transport closed unexpectedly, this is likely due to the process exiting early. If you are developing this MCP server you can add output to stderr (i.e. `console.error('...')` in JavaScript, `print('...', file=sys.stderr)` in python) and it will appear in this log.
2025-04-11T12:09:05.543Z [error] [mcp-server-sample] Server disconnected. For troubleshooting guidance, please visit our [debugging documentation](https://modelcontextprotocol.io/docs/tools/debugging)
```

```text
2025-04-11T12:09:05.526Z [mcp-server-sample] [info] Initializing server...
2025-04-11T12:09:05.540Z [mcp-server-sample] [error] spawn node ENOENT {"context":"connection","stack":"Error: spawn node ENOENT\n    at ChildProcess._handle.onexit (node:internal/child_process:285:19)\n    at onErrorNT (node:internal/child_process:483:16)\n    at process.processTicksAndRejections (node:internal/process/task_queues:82:21)"}
2025-04-11T12:09:05.541Z [mcp-server-sample] [error] spawn node ENOENT {"stack":"Error: spawn node ENOENT\n    at ChildProcess._handle.onexit (node:internal/child_process:285:19)\n    at onErrorNT (node:internal/child_process:483:16)\n    at process.processTicksAndRejections (node:internal/process/task_queues:82:21)"}
2025-04-11T12:09:05.543Z [mcp-server-sample] [info] Server transport closed
2025-04-11T12:09:05.543Z [mcp-server-sample] [info] Client transport closed
2025-04-11T12:09:05.543Z [mcp-server-sample] [info] Server transport closed unexpectedly, this is likely due to the process exiting early. If you are developing this MCP server you can add output to stderr (i.e. `console.error('...')` in JavaScript, `print('...', file=sys.stderr)` in python) and it will appear in this log.
2025-04-11T12:09:05.543Z [mcp-server-sample] [error] Server disconnected. For troubleshooting guidance, please visit our [debugging documentation](https://modelcontextprotocol.io/docs/tools/debugging) {"context":"connection"}
```

何もわからん😇

Issueを調べたところ、似たような問題を発見した。  
[https://github.com/modelcontextprotocol/quickstart-resources/issues/17](https://github.com/modelcontextprotocol/quickstart-resources/issues/17)

自分の環境もnodeをnodenv経由で入れていたため、`claude_desktop_config.json`を以下の通り修正する。

```json
{
    "mcpServers": {
        "mcp-server-sample": {
            "command": "/ABSOLUTE/PATH/TO/.NODENV/FOLDER/.nodenv/shims/node",
            "args": [
                "/ABSOLUTE/PATH/TO/PARENT/FOLDER/mcp-server-sample/build/index.js"
            ]
        }
    }
}
```

この状態で再起動することで無事認識させることができた。

# 動作確認

「tminasenについてあなたの知っていることを教えて下さい。」と訊いてみた。  
結果としては下記のようにMCPサーバで定義した内容を元に回答してくれるようになる。

```markdown
tminasenについての情報を調べてみます。

tminasenについて、Web開発者であるという基本情報を確認することができました。もう少し詳しい情報を調べてみましょう。

tminasenについての情報をまとめると：

1. **職業**: Web開発者

2. **フロントエンド(FE)スキル**:
   - React
   - Angular
   - Tailwind CSS

3. **バックエンド(BE)スキル**:
   - Express
   - Spring Boot

tminasenさんは、フロントエンドとバックエンドの両方のスキルを持つフルスタック開発者であると言えます。ReactやAngularといった現代的なJavaScriptフレームワークを使ったフロントエンド開発と、ExpressやSpring Bootを使ったバックエンド開発の経験をお持ちのようです。
```

ちなみに何も設定していない時は「誰やそれ？」と回答されて終わっていた。

また、FEだけについて訊けばそのことのみ返してくれる。  
「tminasenがFE開発で作業することは可能ですか？可能な場合理由も提示して下さい。」と訊いた結果は以下の通り。

````markdown
tminasenのFE開発の可能性について調査してみましょう。まず、tminasenの情報と特にFEスキルについて確認します。

はい、tminasenはFE開発で作業することが可能です。理由は以下の通りです：

1. tminasenはウェブ開発者である点が基本情報から確認できました
2. FEスキル情報によると、以下の重要なフロントエンド技術を習得しています：
   - React: 最も人気のあるフロントエンドフレームワーク
   - Angular: エンタープライズアプリケーションに適した強力なフレームワーク
   - Tailwind CSS: モダンなUIデザインに広く使われているCSSフレームワーク

これらの技術スタックは現代のフロントエンド開発において非常に重要で、多くのプロジェクトで採用されています。特にReactとAngularは市場シェアの大きい2大フレームワークであり、Tailwind CSSと組み合わせることで効率的なUI開発が可能です。

例えば、TypeScriptとReactを組み合わせた開発では：

```typescript
// React+TypeScriptのコンポーネント例
interface UserProps {
  name: string;
  email: string;
  role: 'admin' | 'user';
}

const UserProfile: React.FC<UserProps> = ({ name, email, role }) => {
  return (
    <div className="p-4 bg-white shadow rounded-lg">
      <h2 className="text-xl font-bold">{name}</h2>
      <p className="text-gray-600">{email}</p>
      <span className={`px-2 py-1 rounded ${role === 'admin' ? 'bg-red-100 text-red-800' : 'bg-blue-100 text-blue-800'}`}>
        {role}
      </span>
    </div>
  );
};
```

このようにtminasenの持つスキルセットは現代のフロントエンド開発に十分対応できるものです。
````

# まとめ
今回はMCPサーバについて調べつつ実際に試してみた。  
思ったよりも簡単にサーバを立てることができたし、Claudeがこちらの情報を使って色々やってくれるのは未来を感じた。  
もっと色々できるものだと思うので引き続き調べていく。  

ここ最近Claudeくんと話しているにハマっているけど、より深くハマれそうでとても楽しい。。。
