Skip to main content
Glama
GraphRAG TypeScript MCP Tools

GraphRAG TypeScript MCP Tools

by Akakinad

GraphRAG TypeScript MCP Tools

TypeScript、Neo4j、MCP TypeScript SDK を使用して構築された GraphRAG MCP サーバーの完全な実装です。このプロジェクトは、グラフを基盤としたツール、リソース、LLM サンプリングや補完などの高度な機能を公開する、本番品質の MCP サーバーを構築する方法を示しています。

このプロジェクトは、Neo4j GraphAcademy — Building GraphRAG TypeScript MCP tools コースの一環として構築されました。


MCP とは?

Model Context Protocol(MCP)は、Anthropic によるオープン標準で、AI エージェント(Claude、Cursor、VS Code Copilot)が外部ツールやデータソースに標準化された方法で接続できるようにします。


Related MCP server: CodeRAG

プロジェクト構造

genai-mcp-build-custom-tools-typescript/ ├── server/ │ └── index.ts ← Main MCP server: 4 tools + 1 resource + sampling + completions ├── strawberry/ │ └── index.ts ← First MCP server: simple countLetters tool ├── solutions/ ← Course reference solutions ├── .vscode/ │ └── mcp.json ← VS Code MCP configuration └── README.md


構築内容

ステップ 1 — 最初の MCP サーバー (strawberry/index.ts)

可能な限りシンプルな MCP サーバーです。ツールは1つ、データベースなし、stdio トランスポートを使用します。

server.registerTool("countLetters", {
  description: "Count occurrences of a letter in the text",
  inputSchema: {
    text: z.string().describe("The text to search in"),
    search: z.string().describe("The letter to count"),
  },
}, async ({ text, search }) => ({
  content: [{
    type: "text",
    text: String(text.toLowerCase().split(search.toLowerCase()).length - 1),
  }],
}));

テスト結果: countLetters("strawberry", "r") → 3

MCP Inspector を使用してテスト済み — MCP サーバーを探索およびテストするためのブラウザベースのツールです。


ステップ 2 — Neo4j 接続(モジュールスコープ)

Python の lifespan コンテキストマネージャとは異なり、TypeScript では モジュールスコープ変数 を使用します。ドライバはファイルの先頭で一度だけ作成され、すべてのツールが直接共有します。

// Created ONCE when file loads — shared by all tools
const driver: Driver = neo4j.driver(
  process.env["NEO4J_URI"] ?? "neo4j://localhost:7687",
  neo4j.auth.basic(
    process.env["NEO4J_USERNAME"] ?? "neo4j",
    process.env["NEO4J_PASSWORD"] ?? "password"
  )
);
const database = process.env["NEO4J_DATABASE"] ?? "neo4j";

SIGINT によるグレースフルシャットダウン:

process.on("SIGINT", async () => {
  await driver.close();
  await server.close();
  process.exit(0);
});

ステップ 3 — ツール 1: graphStatistics

Neo4j 内のすべてのノードとリレーションシップをカウントします。

結果: {"nodes": 28863, "relationships": 332522}


ステップ 4 — ツール 2: getMoviesByGenre

IMDB 評価順にジャンルで映画を検索します。ロギングには console.error() を使用します — stdio サーバーでは決して console.log() を使ってはいけません(JSON-RPC チャネルが破損します)。

server.registerTool("getMoviesByGenre", {
  description: "Get movies by genre from the Neo4j database",
  inputSchema: {
    genre: z.string().describe("The genre to search for (e.g., Action, Comedy, Drama)"),
    limit: z.number().default(10).describe("Maximum number of movies to return"),
  },
}, async ({ genre, limit }) => {
  const { records } = await driver.executeQuery(query,
    { genre, limit: neo4j.int(limit) },  // neo4j.int() for 64-bit integer compatibility
    { database }
  );
  ...
});

ステップ 5 — ツール 3: browse_movies_by_genre(ページネーション)

Neo4j の SKIP と LIMIT を使用したカーソルベースのページネーション:

const skip = parseInt(cursor, 10) || 0;
// Cypher: SKIP $skip LIMIT $limit
const nextCursor = movies.length === pageSize ? String(skip + pageSize) : null;

戻り値:

{
  "genre": "Action",
  "movies": [...],
  "nextCursor": "2",
  "page": 1,
  "pageSize": 2,
  "hasMore": true,
  "count": 2
}

ステップ 6 — リソース: movie://{tmdbId}

ResourceTemplate を使用して TMDB ID で映画の詳細情報を公開します:

server.registerResource(
  "movie",
  new ResourceTemplate("movie://{tmdbId}", { list: undefined }),
  { description: "Get detailed information about a specific movie", mimeType: "application/json" },
  async (uri, { tmdbId }) => {
    // uri.href = "movie://603"
    // returns: contents array with JSON movie data
  }
);

例: movie://603(The Matrix)、movie://13(Forrest Gump)


ステップ 7 — 高度な機能: サンプリング(explainMovieData)

実行中に LLM を呼び出して、生の Neo4j データを自然言語に変換するツール:

const result = await server.server.createMessage({
  messages: [{
    role: "user",
    content: {
      type: "text",
      text: `Describe '${movieData.title}' (${movieData.released})...`,
    },
  }],
  maxTokens: 200,
});

サンプリングなし: {'title': 'Toy Story', 'released': '1995', 'actors': [...]}

サンプリングあり(VS Code Copilot): "Toy Story — バズ・ライトイヤーが新しいお気に入りになったことで居場所を失ったと感じる嫉妬深いカウボーイ人形ウッディを描いた、機知に富んだ面白いアニメーションアドベンチャー..."

注: 低レベルのサーバーで capability を設定する必要があります:

server.server["_capabilities"] = { ...server.server["_capabilities"], completions: {} };

ステップ 8 — 高度な機能: 補完

ジャンルパラメータに対するリアルタイムの自動補完候補 — ユーザーが入力する際に Neo4j にクエリを実行します:

import { CompleteRequestSchema } from "@modelcontextprotocol/sdk/types.js";

server.server.setRequestHandler(CompleteRequestSchema, async (request) => {
  if (request.params.argument.name === "genre") {
    const { records } = await driver.executeQuery(
      `MATCH (g:Genre)
       WHERE g.name STARTS WITH $prefix
       RETURN g.name AS name
       ORDER BY name ASC LIMIT 10`,
      { prefix: request.params.argument.value },
      { database }
    );
    return { completion: { values: records.map(r => r.get("name")) } };
  }
  return { completion: { values: [] } };
});

Python 版との主な違い

概念

Python (FastMCP)

TypeScript (McpServer)

ツール登録

@mcp.tool() デコレータ

server.registerTool() メソッド

共有状態

Lifespan コンテキストマネージャ

モジュールスコープ変数

ドライバアクセス

ctx.request_context.lifespan_context.driver

driver(直接)

ロギング

await ctx.info()

console.error()

サンプリング

ctx.session.create_message()

server.server.createMessage()

補完

@server.completion()

server.server.setRequestHandler(CompleteRequestSchema)

ファイル構造

機能ごとにファイルを分離

すべてを1つの index.ts に

数値パラメータ

Python の int 型ヒント

neo4j.int() ラッパーが必要

プロンプトパラメータ

int, str, float

常に z.string() を使用し、手動でパース


セットアップ

前提条件

  • Node.js 20+

  • npm

  • Neo4j Sandbox — sandbox.neo4j.com の Recommendations データセット

インストール

git clone https://github.com/Akakinad/genai-mcp-build-custom-tools-typescript
cd genai-mcp-build-custom-tools-typescript
npm install

認証情報の設定

cat > server/.env << EOF
NEO4J_URI=bolt://your-sandbox-ip:7687
NEO4J_USERNAME=neo4j
NEO4J_PASSWORD=your-password
NEO4J_DATABASE=neo4j
EOF

セットアップの確認

npx tsx client/test_environment.ts
# Expected: All checks passed!

実行

MCP Inspector でテストする(ブラウザ UI)

cd server
npx @modelcontextprotocol/inspector npx tsx index.ts

ターミナルに表示された URL を開く → Connect → Tools タブ → List Tools → ツールを選択 → Run Tool。

AI エディタで使用するためのサーバーを実行

cd server
npx tsx index.ts

VS Code 設定 (.vscode/mcp.json)

{
  "servers": {
    "movies-ts": {
      "type": "stdio",
      "command": "npx",
      "args": ["tsx", "/absolute/path/to/server/index.ts"]
    }
  }
}

VS Code Copilot でテストする

movies-ts MCP ツールを使用して映画「Toy Story」を説明してください movies-ts MCP ツールを使用してアクション映画を検索してください movies-ts MCP ツールを使用してグラフ統計を取得してください


コース

ラーニングパス: Generative AI & GraphRAG

コース: Building GraphRAG TypeScript MCP tools


Building GraphRAG TypeScript MCP Tools

GraphAcademy コース Building GraphRAG TypeScript MCP Tools のコンパニオンリポジトリです。

受講生は、Neo4j グラフデータベースに接続する MCP(Model Context Protocol)サーバーを構築し、AI アシスタントで使用するツールとリソースを公開します。

はじめに

  1. .env.example を .env にコピーし、Neo4j の接続情報で値を更新します。

  2. 依存関係をインストール:

npm install
  1. サーバーを起動:

npm start
  1. MCP Inspector でサーバーを検査:

npm run inspect

ソリューション

solutions/ ディレクトリには、各レッスンのチェックポイントの完成コードが含まれています。

Available Tools

4 tools
browse_movies_by_genreC

Browse movies in a genre with pagination support

Inputs: genre (required), cursor, pageSize.

explainMovieDataA

Get a natural language explanation of movie data using LLM sampling

Inputs: movieTitle (required).

getMoviesByGenreC

Get movies by genre from the Neo4j database

Inputs: genre (required), limit.

graphStatisticsB

Count the number of nodes and relationships in the graph

Inputs: no named parameters.

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

Loading tool schema changelog…

    TDQS

    C2.9/5.0

    Scored across 4 tools

    Disambiguation2/5

    The two tools for movies by genre (getMoviesByGenre and browse_movies_by_genre) have overlapping purposes; the only distinction is pagination support, which may cause an agent to misselect. Other tools are distinct.

    Naming Consistency2/5

    Mixes camelCase (getMoviesByGenre, explainMovieData, graphStatistics) and snake_case (browse_movies_by_genre) with different verb conventions ('get' vs 'browse'), showing inconsistency.

    Tool Count3/5

    With only 4 tools, the surface is minimal but perhaps appropriate for a read-only movie graph query server. It borders on being too few but is not extreme.

    Completeness2/5

    Missing basic operations like fetching a specific movie by ID, listing all genres, or querying actors/relationships. The tool set covers only a small subset of expected graph queries, leaving significant gaps.

    Maintenance

    ActivityInactive
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      Not graded
      quality
      D
      maintenance
      An MCP server that transforms codebases into knowledge graphs using Neo4J, enabling AI assistants to understand code structure, relationships, and metrics for more context-aware assistance.
      28
      MIT
    • A
      license
      A
      quality
      D
      maintenance
      An MCP server that enables LLMs to perform semantic and fulltext searches within Neo4j while executing complex, search-augmented Cypher queries for GraphRAG applications. It provides tools for database schema discovery and supports multi-provider embeddings to facilitate advanced graph traversals.
      5
      3
      MIT
    • A
      license
      Not graded
      quality
      C
      maintenance
      MCP server for Neo4j graph database operations, enabling Cypher queries, node/relationship management, and schema discovery.
      1
      BSD 3-Clause