1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

この記事は何?

MCP Server を実装する際に都度調べるのも面倒なので、個人用途でテンプレ化しました。

多分 Mac, Linux でしか動きません 🙏
(win では package.json の scripts, bin あたりが動かなそう)

そもそも MCP とは?

以前に ↓ の記事を書いたので、よければご覧下さい。

実装

例のごとく、公式のチュートリアルがあります。全然難しくないです。

そこから全てを削ぎ落として最小化した TypeScript ベースのテンプレリポジトリを作りました。

実際に MCP Server 本体の TypeScript コードは次の通りです。

このコードでは get_current_time という UTC 現在時刻を返す tools を提供する MCP Server を実装しています。

src/index.ts
#!/usr/bin/env node

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

// Create server instance
const server = new McpServer({
  name: "time",
  version: "1.0.0",
  capabilities: {
    resources: {},
    tools: {},
  },
});

// Register "get_current_time" tools
server.tool(
  "get_current_time",  // tools 名
  "Get the current time",  // tools の説明文.
  {},  // tools に引数がある場合は、ここで zod 定義をする.
  async () => {  // tools 実装.
    const currentTime = new Date().toISOString();

    return {
      content: [
        {
          type: "text",
          text: currentTime,
        },
      ],
    };
  },
);

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);
});

使い方

Claude for Desktop を例に、本自作 MCP Server を動かしてみます。

以下の Claude for Desktop の設定ファイルを開きます。

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

次の設定を追記しましょう。

~/Library/Application Support/Claude/claude_desktop_config.json
{
  "mcpServers": {
    "time": {
      "command": "/path/to/node (※変えてね!)",
      "args": [
        "/path/to/example-mcp-server/build/index.js (※変えてね!)"
      ]
    }
  }
}

本格稼働する場合は npx (npm) で公開するところまでした方がよいですね。
ここではあくまで開発用途でローカル利用するところまでに留めます。

Claude for Desktop を起動すると、MCP Server が無事に起動した場合は以下のハンマーアイコンに tools 数が表示されます。

image.png

実際に現在時刻を問い合わせてみると、きちんと回答してくれます。UTCなのが残念ですが...😅

image.png

1
4
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
1
4

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?