Skip to main content
Glama
Akakinad

GraphRAG TypeScript MCP Tools

by Akakinad

GraphRAG TypeScript MCP Tools

A complete implementation of a GraphRAG MCP server built with TypeScript, Neo4j, and the MCP TypeScript SDK. This project demonstrates how to build production-quality MCP servers that expose graph-backed tools, resources, and advanced features like LLM sampling and completions.

Built as part of the Neo4j GraphAcademy — Building GraphRAG TypeScript MCP tools course.


MCP란 무엇인가?

Model Context Protocol(MCP)는 Anthropic이 만든 개방형 표준으로, AI 에이전트(Claude, Cursor, VS Code Copilot)가 외부 도구와 데이터 소스에 표준화된 방식으로 연결할 수 있게 해줍니다.


프로젝트 구조

genai-mcp-build-custom-tools-typescript/ ├── server/ │ └── index.ts ← 메인 MCP 서버: 도구 4개 + 리소스 1개 + 샘플링 + 자동 완성 ├── strawberry/ │ └── index.ts ← 첫 번째 MCP 서버: 간단한 countLetters 도구 ├── solutions/ ← 과정 참조 솔루션 ├── .vscode/ │ └── mcp.json ← VS Code MCP 구성 └── README.md


구축된 내용

1단계 — 첫 번째 MCP 서버 (strawberry/index.ts)

가장 단순한 MCP 서버입니다. 도구 하나, 데이터베이스 없음, 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의 SKIPLIMIT를 사용하는 커서 기반 페이지네이션:

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 — Buzz Lightyear가 새로운 인기 캐릭터가 되면서 자리가 밀려난 느낌을 받는 질투심 많은 카우보이 인형 Woody에 관한 영리하고 재미있는 애니메이션 모험..."

참고: 저수준 서버에 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)

파일 구조

기능별 별도 파일

모든 것이 하나의 index.ts에 있음

숫자 매개변수

Python int 타입 힌트

neo4j.int() 래퍼 필요

프롬프트 매개변수

int, str, float

항상 z.string(), 수동으로 파싱


설정

사전 요구 사항

설치

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/ 디렉토리에는 각 레슨 체크포인트에 대한 완성된 코드가 포함되어 있습니다.

-
license - not tested
-
quality - not tested
C
maintenance

Maintenance

Maintainers
Response time
Release cycle
Releases (12mo)
Commit activity

Resources

Unclaimed servers have limited discoverability.

Looking for Admin?

If you are the server author, to access and configure the admin panel.

Related MCP Connectors

  • MCP server for AI dialogue using various LLM models via AceDataCloud

  • MCP server for Argo RPG Platform — connects AI assistants to campaign data via OAuth2

  • Self-hosted MCP gateway: turn any API, database or MCP server into AI connectors — no code.

View all MCP Connectors

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/Akakinad/genai-mcp-build-custom-tools-typescript'

If you have feedback or need assistance with the MCP directory API, please join our Discord server