elysiajs-mcp

elysiajs-mcp

An MCP server plugin for the Elysia web framework, enabling AI clients to connect via Streamable HTTP transport with stateful or stateless sessions and authentication.

Category
访问服务器

README

elysiajs-mcp

npm version CI License: MIT

Model Context Protocol (MCP) server transport and plugin for the Elysia web framework (Bun).

Connect AI clients to your Elysia app over the MCP Streamable HTTP transport. Built on the official @modelcontextprotocol/sdk web-standard transport, with an idiomatic Elysia plugin that handles session lifecycle for you.

Features

  • mcp() plugin — mount a full MCP server in one line, with automatic stateful (per-session) and stateless modes.
  • StreamableHTTPTransport — a low-level transport you can wire up manually (mirrors the @hono/mcp API).
  • Permissive Accept header handling by default — works out of the box with Gemini CLI, the Java MCP SDK, Open WebUI, and curl. Toggle strict mode if you prefer.
  • MemoryEventStore — in-memory event store enabling SSE resumability.
  • Auth helpersbearerAuth() for token validation and mcpAuthMetadata() for the /.well-known OAuth discovery endpoints.
  • Runs on any web-standard runtime (Bun, Node, Deno, Workers).

Install

bun add elysiajs-mcp @modelcontextprotocol/sdk elysia

Quick start

import { Elysia } from "elysia";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { z } from "zod";
import { mcp } from "elysiajs-mcp";

new Elysia()
  .use(
    mcp({
      server: () => {
        const server = new McpServer({ name: "my-server", version: "1.0.0" });

        server.registerTool(
          "greet",
          {
            description: "Greet someone by name",
            inputSchema: { name: z.string().default("world") },
          },
          async ({ name }) => ({
            content: [{ type: "text", text: `Hello, ${name}!` }],
          }),
        );

        return server;
      },
    }),
  )
  .listen(3000);

Connect any MCP client (e.g. the MCP Inspector) to http://localhost:3000/mcp.

How it works

mcp() mounts a single .all('/mcp') route. A server() factory is invoked for every new session (stateful mode) or every request (stateless mode), so each session gets isolated tools, prompts, and resources.

Option Default Description
server (required) Factory returning an MCP Server / McpServer.
path '/mcp' Endpoint path.
sessionIdGenerator () => crypto.randomUUID() Pass undefined for stateless mode.
strictAcceptHeader false Strictly enforce the MCP Accept header spec.
enableJsonResponse false Return JSON instead of SSE for POST requests.
eventStore none Provide a MemoryEventStore (or your own) for resumability.
auth none (request) => AuthInfo | Response | undefined hook.
onsessioninitialized none Called when a session is created.
onsessionclosed none Called when a session is closed via DELETE.

Stateful vs. stateless

// Stateful (default): one server + transport kept alive per session.
mcp({ server: () => new McpServer({ name: "s", version: "1" }) });

// Stateless: a fresh server + transport per request, torn down after.
mcp({ server: () => new McpServer({ name: "s", version: "1" }), sessionIdGenerator: undefined });

Resumability (event store)

Pass an eventStore so clients that disconnect can resume missed messages via Last-Event-ID.

import { mcp, MemoryEventStore } from 'elysiajs-mcp'

mcp({ server: () => …, eventStore: new MemoryEventStore() })

MemoryEventStore keeps the last 100 streams × 100 events by default (both configurable).

Auth

Bearer tokens

import { mcp, bearerAuth } from 'elysiajs-mcp'

new Elysia().use(
  mcp({
    server: () => …,
    auth: bearerAuth({
      require: true,
      verify: async (token) => {
        const user = await verifyToken(token)
        return user ? { token, clientId: user.id, scopes: user.scopes } : undefined
      },
    }),
  })
)

OAuth discovery endpoints

Advertise where clients should authenticate (RFC 8414 / RFC 9728):

import { mcpAuthMetadata } from "elysiajs-mcp";

new Elysia().use(
  mcpAuthMetadata({
    issuerUrl: "https://auth.example.com",
    resourceServerUrl: new URL("http://localhost:3000/mcp"),
  }),
);

This serves /.well-known/oauth-authorization-server and /.well-known/oauth-protected-resource.

Low-level transport

If you need full control (mirrors @hono/mcp's API):

import { Elysia } from "elysia";
import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
import { StreamableHTTPTransport } from "elysiajs-mcp";

const server = new McpServer({ name: "low-level", version: "1.0.0" });
const transport = new StreamableHTTPTransport({ sessionIdGenerator: () => crypto.randomUUID() });

new Elysia().all("/mcp", async ({ request }) => {
  if (!server.isConnected()) await server.connect(transport);
  return transport.handleRequest(request);
});

StreamableHTTPTransport accepts the same options as the SDK's transport, plus strictAcceptHeader.

API

mcp(options): Elysia

Mount an MCP Streamable HTTP server.

StreamableHTTPTransport

Extends WebStandardStreamableHTTPServerTransport. Adds strictAcceptHeader (default false).

MemoryEventStore

In-memory EventStore implementation with bounded ring buffers.

bearerAuth(options) / unauthorizedResponse(request, url?)

Bearer-token auth extractor (401 challenge helper).

mcpAuthMetadata(options) / createOAuthMetadata(options)

Elysia plugin + helper serving OAuth discovery metadata.

Scripts

bun run lint         # oxlint
bun run lint:fix     # oxlint --fix
bun run format       # oxfmt (write)
bun run format:check # oxfmt --check
bun run typecheck    # tsc --noEmit
bun run check        # lint + format:check + typecheck
bun test             # run the test suite
bun run dev          # run the example server (example/server.ts)
bun run build        # bundle to dist/

Credits & license

Inspired by @hono/mcp by Aditya Mathur.

License

MIT © Francisco Pizarro

推荐服务器

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 模型以安全和受控的方式获取实时的网络信息。

官方
精选