MCP Multi-Context Hook Generator

MCP Multi-Context Hook Generator

Automatically generates typed React hooks for Next.js projects by crawling API routes, GraphQL queries, and components. Analyzes pages to suggest optimal render modes (SSR/CSR/ISR) and produces comprehensive documentation with AI-powered guidance.

Category
访问服务器

README

This repo is fully modular, repo-agnostic, and can adapt dynamically to any frontend project.

Full plan for a ready-to-use modular MCP prototype repo that adapts to any frontend project and can generate typed code matching its conventions. I’ll outline the repo structure, include all core files, and provide runnable code.

MCP - Multi-Context Hook Generator

This tool automatically generates typed React hooks for your Next.js + TypeScript project, supporting:

  • Next.js REST API routes
  • API client functions
  • GraphQL queries & mutations
  • SWR / SWR Infinite
  • React Query

Features

  • Auto-imports API client functions: No manual injection needed
  • GraphQL extraction: Generates hooks with inline gql strings
  • SWR Infinite support: For REST and GraphQL paginated queries
  • Typed hooks: Fully typed with return types from your API
  • Flexible: Works for any repo structure

Installation

npm install swr @tanstack/react-query @apollo/client ts-morph glob


Repository Structure

MCP-Server ├─ crawler/ │ └─ api.ts │ • Scans app/api and api/ folders │ • Detects exported functions │ • Extracts: │ - methods │ - responseType │ - kind (REST / GraphQL) │ - environment (server / client / universal) │ • Returns ApiRoute[] │ ├─ generator/ │ └─ hooks.ts │ • Consumes ApiRoute[] │ • Generates typed hooks: │ - useSWR / useSWRInfinite (client) │ - useQuery / useMutation (GraphQL) │ - server-only functions │ • Supports REST, API clients, GraphQL queries/mutations │ ├─ mcp/ │ ├─ pageAnalyzer.ts │ │ • Scans app/pages or app/ for page.tsx files │ │ • Detects which hooks are used in each page │ │ • Reads environment of each hook │ │ • Infers render mode: SSR / ISR / CSR / SSG │ │ │ └─ generateDocs.ts │ • Produces Markdown per page: │ - Suggested render mode │ - Reasoning │ - Hook usage table │ - Optional SSR/ISR boilerplate │ ├─ CLI / entry point (mcp-server.ts) │ • Runs pipeline: │ 1. crawlApi(rootDir) │ 2. generateHooks(apiRoutes, options) │ 3. analyzePages(rootDir, apiRoutes) │ 4. generateDocs(outputDir, analyses) │ • Output: │ - hooks.ts (typed hooks) │ - mcp-docs/ (developer documentation) │ └─ config/ └─ mcp.config.ts • Options: - SWR infinite usage - GraphQL infinite queries - Page folders to analyze - Output directories


How the Modules Interact

Crawler (api.ts)

Inputs: rootDir of project

Outputs: ApiRoute[] with method names, environment, response type, kind

Hooks Generator (hooks.ts)

Inputs: ApiRoute[]

Outputs: hooks.ts (typed, environment-aware hooks)

Environment-aware: generates server-only, client-only, or universal hooks

Page Analyzer (pageAnalyzer.ts)

Inputs: ApiRoute[] + page files (page.tsx)

Outputs: PageAnalysis[] with inferred render mode

Logic:

Mixed hooks → SSR

Server-only → SSR/ISR

Client-only → CSR

No hooks → SSG

Docs Generator (generateDocs.ts)

Inputs: PageAnalysis[]

Outputs: Markdown docs per page

Includes:

Render mode suggestion

Reason

Hook usage table

Optional SSR/ISR boilerplate

MCP-Server CLI

Runs the full pipeline in sequence

Provides a developer-ready output:

Hooks to import and use

Documentation to guide render mode choices

How to Run

pnpm install
pnpm start           # runs full MCP pipeline
pnpm crawl           # runs only crawler
pnpm generate-hooks  # runs only hooks generator

MCP automatically crawls the project: components, API routes, GraphQL, types

AI tools (Copilot/ChatGPT) can query MCP for typed resources.

Use scaffold-swr-hook tool to generate typed hooks dynamically.

How It Works

1.Run MCP → it scans the repo and builds a universal project model. 2.Use tools dynamically via MCP API: SWR Hook:

{
    "tool":"scaffold-swr-hook",
    "args":{"path":"/api/users","typeName":"User[]"}
}


GraphQL Hook:

{
    "tool":"scaffold-graphql-hook",
    "args":{
        "opName":"GetUser",
        "type":"query",
        "variablesType":"GetUserQueryVariables",
        "responseType":"GetUserQuery"
    }
}

Page:

{
    "tool":"scaffold-page",
    "args":{"pageName":"Dashboard","components":["Navbar","UserCard"]}
}

3.MCP generates typed hooks or pages matching repo style. 4.AI (Copilot/Cursor) can now query MCP for the latest types, components, API routes.

How it Works

Crawls the hooks/ folder (or any custom folder).

Detects all .ts/.tsx files.

Uses ts-morph to parse TypeScript AST.

Filters functions starting with use (React hook convention).

Infers return types if explicitly typed.

Returns an array of:

[ { name: "useUser", returnType: "{ data: User | undefined; error: any; isLoading: boolean }", path: "hooks/useUser.ts" }, { name: "useAuth", returnType: "{ user: AuthUser | null; login: Function; logout: Function }", path: "hooks/useAuth.ts" } ]

1️⃣ Basic run (full MCP pipeline, no AI)

Run all steps: crawl APIs, generate hooks, analyze pages, generate docs

pnpm start --all

Equivalent with npm:

npm run start -- --all

2️⃣ Dry-run mode (preview only, no files written) pnpm start --all --dry-run

Useful for testing pipeline without touching your repo

Logs hook and doc previews to console

3️⃣ Enable AI cursor suggestions (Copilot / OpenAI) pnpm start --all --use-cursor-assist --ai-agent copilot

Adds AI guidance comments in hooks (generateHooks.ts)

Adds AI suggestions in page docs (generateDocs.ts)

You can also pass openai in the CLI if you extend the CLI parsing for an API key

4️⃣ Disable auto render inference pnpm start --all --no-auto-infer

Keeps your existing suggestedRenderMode for pages

Useful if you want manual control for SSR/CSR/ISR

5️⃣ Combine dry-run + AI + custom agent pnpm start --all --dry-run --use-cursor-assist --ai-agent openai

Safe preview

AI suggestions included

No files are written

✅ Notes

All flags are optional; --all defaults to running everything.

You can mix and match: --hooks --docs to run only specific steps.

Dry-run is especially useful for CI pipelines, so you can validate MCP output without committing.

MCP CLI Command Matrix Scenario Command Notes Full run, default pnpm start --all Runs all steps: crawl APIs, generate hooks, analyze pages, generate docs. Uses default suggested render modes, no AI guidance. Full run, dry-run preview pnpm start --all --dry-run Previews hooks/docs in console, no files written. Mirrors PR behavior in CI. Enable AI guidance (Copilot) pnpm start --all --use-cursor-assist --ai-agent copilot Adds AI suggestions in hooks/docs. No dry-run. Enable AI guidance (OpenAI) pnpm start --all --use-cursor-assist --ai-agent openai Uses OpenAI agent for suggestions (requires API integration if implemented). Disable auto render inference pnpm start --all --no-auto-infer Keeps your existing suggestedRenderMode values, ignores auto-detection based on server hooks. Partial run (only hooks) pnpm start --hooks Only generates typed hooks, skips pages/docs analysis. Partial run (only docs) pnpm start --docs Only generates docs from previous analysis/hooks, skips API crawling. Dry-run + AI guidance pnpm start --all --dry-run --use-cursor-assist --ai-agent copilot Previews all generated content with AI suggestions, safe for dev branch testing. Custom AI agent pnpm start --all --ai-agent custom Placeholder for your own AI logic or local LLM integration. Tips for Devs

Dry-run first when testing new hooks or pages.

Use AI guidance to get suggested SSR/ISR/CSR render modes.

Partial runs are useful for fast iteration (--hooks or --docs).

Auto-infer render should usually be on (--no-auto-infer only if you want manual override).

You can combine multiple flags, e.g.:

pnpm start --hooks --use-cursor-assist --ai-agent copilot --dry-run

🛠️ MCP Developer Guide

The Modular Context Protocol (MCP) pipeline helps developers crawl APIs, generate typed hooks, analyze pages, and produce documentation automatically for Next.js + React projects.

This guide explains local usage, AI features, and CI integration.

1️⃣ Installation

Clone your project

git clone <your-repo-url> cd <your-repo>

Install dependencies using pnpm (recommended)

npm install -g pnpm pnpm install

✅ MCP is fully compatible with npm or yarn, but pnpm is recommended for speed and caching.

2️⃣ Running MCP Locally Full pipeline pnpm start --all

Crawls APIs

Generates typed hooks (hooks/)

Analyzes pages

Generates docs (mcp-docs/) with suggested render modes (CSR/SSR/ISR)

Dry-run (preview only) pnpm start --all --dry-run

Logs hooks/docs previews in console

Does not write any files

Ideal for testing changes on feature branches

Enable AI guidance pnpm start --all --use-cursor-assist --ai-agent copilot

Adds AI suggestions for render mode and performance guidance

Supported agents: copilot, openai, custom

Combine with --dry-run to safely preview AI suggestions without writing files.

Disable auto render inference pnpm start --all --no-auto-infer

Keeps your existing suggestedRenderMode

MCP won’t infer SSR/CSR/ISR based on server hooks

Partial runs pnpm start --hooks # Only generate hooks pnpm start --docs # Only generate docs pnpm start --analyze # Only analyze pages

Useful for fast iteration during development.

3️⃣ CI/CD Integration

MCP integrates with GitHub Actions via .github/workflows/mcp.yml

Feature branches run in dry-run mode to preview changes safely

Main branch runs real generation and commits updated hooks/docs automatically

Key features

  • dry-run on PRs/feature branches
  • AI suggestions enabled
  • Node_modules + ts-morph cache for large projects
  • Automatic commit on main branch

4️⃣ Output Structure hooks/ # Generated typed hooks for all API routes mcp-docs/ # Markdown docs per page + summary.md

Each page doc includes:

Suggested render mode (CSR/SSR/ISR)

Hooks used with environment type (client/server/universal)

Optional SSR/ISR boilerplate code

⚡ AI guidance comments (if enabled)

5️⃣ Tips for Developers

Always run dry-run first when testing new hooks or pages.

Use AI guidance to pick optimal render modes.

Partial runs help speed up iteration (--hooks / --docs).

Feature branches → dry-run; Main branch → commit updates automatically.

Large projects: caching node_modules and .mcp-cache speeds up MCP significantly.

This README ensures your devs can run MCP locally exactly like CI and take advantage of AI suggestions safely.

推荐服务器

Baidu Map

Baidu Map

百度地图核心API现已全面兼容MCP协议,是国内首家兼容MCP协议的地图服务商。

官方
精选
JavaScript
Playwright MCP Server

Playwright MCP Server

一个模型上下文协议服务器,它使大型语言模型能够通过结构化的可访问性快照与网页进行交互,而无需视觉模型或屏幕截图。

官方
精选
TypeScript
Magic Component Platform (MCP)

Magic Component Platform (MCP)

一个由人工智能驱动的工具,可以从自然语言描述生成现代化的用户界面组件,并与流行的集成开发环境(IDE)集成,从而简化用户界面开发流程。

官方
精选
本地
TypeScript
Audiense Insights MCP Server

Audiense Insights MCP Server

通过模型上下文协议启用与 Audiense Insights 账户的交互,从而促进营销洞察和受众数据的提取和分析,包括人口统计信息、行为和影响者互动。

官方
精选
本地
TypeScript
VeyraX

VeyraX

一个单一的 MCP 工具,连接你所有喜爱的工具:Gmail、日历以及其他 40 多个工具。

官方
精选
本地
graphlit-mcp-server

graphlit-mcp-server

模型上下文协议 (MCP) 服务器实现了 MCP 客户端与 Graphlit 服务之间的集成。 除了网络爬取之外,还可以将任何内容(从 Slack 到 Gmail 再到播客订阅源)导入到 Graphlit 项目中,然后从 MCP 客户端检索相关内容。

官方
精选
TypeScript
Kagi MCP Server

Kagi MCP Server

一个 MCP 服务器,集成了 Kagi 搜索功能和 Claude AI,使 Claude 能够在回答需要最新信息的问题时执行实时网络搜索。

官方
精选
Python
e2b-mcp-server

e2b-mcp-server

使用 MCP 通过 e2b 运行代码。

官方
精选
Neon MCP Server

Neon MCP Server

用于与 Neon 管理 API 和数据库交互的 MCP 服务器

官方
精选
Exa MCP Server

Exa MCP Server

模型上下文协议(MCP)服务器允许像 Claude 这样的 AI 助手使用 Exa AI 搜索 API 进行网络搜索。这种设置允许 AI 模型以安全和受控的方式获取实时的网络信息。

官方
精选