0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

Model Context Protocolを動かしてみる

Last updated at Posted at 2025-04-02

はじめに

Anthropicが開発した「Model Context Protocol (MCP)」は、AIモデル(特に大規模言語モデル、LLM)が外部のデータソースやツールと統合するためのプロトコルです。このプロトコルは、AIアプリケーションが必要なコンテキストを取得し、外部システムでアクションを実行するための標準化された方法を提供します。また、MCPサーバーごとに明確な権限設定が可能であり、安全性とプライバシーを重視した設計となっています。初期段階ではローカル環境での利用が推奨されており、今後クラウド対応が進む予定です。Python、TypeScript、Java/Kotlinなど複数の言語向けSDK(https://github.com/modelcontextprotocol )が提供されています。

APIとの違いなどの図がわかりやすかった

プロトコルの説明であるとか、APIの違いであるとか。プロトコルとAPIの違いってあまりこれまで考えたことなかったけれどこうした説明はとてもわかりやすい。

スクリーンショット 2025-04-15 10.36.30.png

スクリーンショット 2025-04-15 10.36.38.png

技術的な仕組み

MCPは以下の主要コンポーネントで構成されています

IMG_0441.jpeg

MCP Host with MCP Client Server との 1:1 接続を維持するプロトコル クライアント
MCP Server: 標準化されたモデル コンテキスト プロトコルを通じて特定の機能を公開する軽量プログラム
Local Resource: MCP Server が安全にアクセスできるコンピュータのリソース
Remote Resource: MCP Server が接続できるインターネット経由 (API 経由など) で利用可能なリソース

Clientの一覧は下記のような感じ。

IMG_0442.jpeg

現状は、ClientとしてのClaude DesktopのMPCはマシン上で実行されているローカルServerへのみのアクセスであるため、ServerはYour Computerの中にある必要がある。

Servers

MCP Serverは、公式サーバーと、コミュニティサーバーの2種類があります。

公式サーバー
https://github.com/modelcontextprotocol/servers?tab=readme-ov-file

コミュニティサーバー
https://github.com/punkpeye/awesome-mcp-servers

チュートリアル

動作確認のために一番簡単なsqliteを活用したサンプルを実行してみます


brew install uv git sqlite3


# Create a new SQLite database
sqlite3 ~/fruits.db <<EOF
CREATE TABLE fruits (
  id INTEGER PRIMARY KEY,
  name TEXT,
  price REAL
);

INSERT INTO fruits (name, price) VALUES
  ('リンゴ', 300),
  ('バナナ', 200),
  ('オレンジ', 320),
  ('いちご', 1200),
  ('パイナップル', 600),
  ('スイカ', 800),
  ('ブドウ', 1000);
EOF

sqlite3 ~/fruits.db "SELECT * FROM fruits;"

code ~/Library/Application\ Support/Claude/claude_desktop_config.json

{
  "mcpServers": {
    "sqlite": {
      "command": "uvx",
      "args": ["mcp-server-sqlite", "--db-path", "/Users/user-name/fruits.db"]
    }
  }
}

Claudeの設定のところにsqliteが表示されている状態で準備完了です

スクリーンショット 2025-04-10 9.27.48.png

SQLite データベースに接続して、果物の名前と価格のリストを表示して!と質問します

スクリーンショット 2025-04-10 9.29.44.png

ちなみに重複データを入れておいたのですが、出力する時には排他した状態で出してくれています

スクリーンショット 2025-04-10 9.29.54.png

元データからも、重複データをそれらを排他するようにお願いします

スクリーンショット 2025-04-10 9.31.07.png

すると、一時テーブルを作成して、重複データを削除してくれています

スクリーンショット 2025-04-10 9.31.54.png

コンソールでも確認するとしっかり削除されています

スクリーンショット 2025-04-10 9.31.41.png

プログラム例

Python SDKを使用して簡単なMCPサーバーを構築できます。以下は基本的なコード例です:

javascript index.js

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: "oreore-encryption",
    version: "1.0.0",
    capabilities: {
        resources: {},
        tools: {},
    },
});

server.tool(
    "oreore-encryption-3numbers",
    "3つの数からオレオレ暗号を作る",
    {
        a: z.number().describe("数1"),
        b: z.number().describe("数2"),
        c: z.number().describe("数3"),
    },
    async ({ a, b, c }) => {
        return {
            content: [
                {
                    type: "text",
                    text: `${a * b * c + a * c + b}`,
                },
            ],
        };
    },
);

async function main() {
    const transport = new StdioServerTransport();
    await server.connect(transport);
}

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

スクリーンショット 2025-04-14 16.34.39.png

debug

inspectorを起動することでデバッグができますー

$ npx -y @modelcontextprotocol/inspector node ./build/index.js

スクリーンショット 2025-04-14 16.56.23.png

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?