Spaces:
Running
Running
Download server.js from marqueeH/BacklogMCP: direct link, hf CLI and curl.
- Browser
- Download file 29.5 kB
-
https://huggingface.co/spaces/marqueeH/BacklogMCP/resolve/main/server.js
- Command line
-
hf download hf://spaces/marqueeH/BacklogMCP/server.js
-
curl -L -o server.js https://huggingface.co/spaces/marqueeH/BacklogMCP/resolve/main/server.js
29.5 kB
| import express from "express"; | |
| import crypto from "crypto"; | |
| import { SignJWT, jwtVerify } from "jose"; | |
| import { z } from "zod"; | |
| import { Backlog } from "backlog-js"; | |
| import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js"; | |
| import { StreamableHTTPServerTransport } from "@modelcontextprotocol/sdk/server/streamableHttp.js"; | |
| import { isInitializeRequest } from "@modelcontextprotocol/sdk/types.js"; | |
| const app = express(); | |
| app.use(express.json()); | |
| app.use(express.urlencoded({ extended: false })); | |
| const PORT = Number(process.env.PORT || 7860); | |
| // ====== ENV ====== | |
| const BACKLOG_DOMAIN = process.env.BACKLOG_DOMAIN; // ex: te-cr.backlog.com | |
| const BACKLOG_API_KEY = process.env.BACKLOG_API_KEY; | |
| const CLIENT_ID = process.env.OAUTH_CLIENT_ID; // ex: chatgpt-mcp | |
| const CLIENT_SECRET = process.env.OAUTH_CLIENT_SECRET; | |
| const JWT_SECRET_RAW = process.env.JWT_SIGNING_SECRET; | |
| if (!CLIENT_ID || !CLIENT_SECRET || !JWT_SECRET_RAW) { | |
| console.error("Missing env: OAUTH_CLIENT_ID / OAUTH_CLIENT_SECRET / JWT_SIGNING_SECRET"); | |
| process.exit(1); | |
| } | |
| const JWT_SECRET = new TextEncoder().encode(JWT_SECRET_RAW); | |
| // Backlog client (optional - only if BACKLOG_DOMAIN and BACKLOG_API_KEY are set) | |
| let backlogClient = null; | |
| if (BACKLOG_DOMAIN && BACKLOG_API_KEY) { | |
| backlogClient = new Backlog({ host: BACKLOG_DOMAIN, apiKey: BACKLOG_API_KEY }); | |
| console.log(`[Backlog] Client initialized for domain: ${BACKLOG_DOMAIN}`); | |
| } | |
| // ====== LOG ====== | |
| app.use((req, res, next) => { | |
| const auth = req.headers.authorization ? `present(len=${req.headers.authorization.length})` : "none"; | |
| const ct = req.headers["content-type"] || "none"; | |
| console.log(`[REQ] ${req.method} ${req.originalUrl} ct=${ct} auth=${auth}`); | |
| res.on("finish", () => console.log(`[RES] ${req.method} ${req.originalUrl} -> ${res.statusCode}`)); | |
| next(); | |
| }); | |
| // ====== HELPERS ====== | |
| function absBase(req) { | |
| const proto = (req.headers["x-forwarded-proto"] || "https").toString(); | |
| const host = (req.headers["x-forwarded-host"] || req.headers.host).toString(); | |
| return `${proto}://${host}`.replace(/\/+$/, ""); | |
| } | |
| /** | |
| * ChatGPTが /sse をOAuthのベース扱いすることがあるため、 | |
| * 叩かれたパスに応じて issuer/base を切り替える。 | |
| */ | |
| function oauthBase(req) { | |
| const b = absBase(req); | |
| const p = (req.originalUrl || "").toString(); | |
| if (p.startsWith("/sse/")) return `${b}/sse`; | |
| if (p.includes("/.well-known/") && p.endsWith("/sse")) return `${b}/sse`; | |
| return b; | |
| } | |
| function oauthMetadata(req) { | |
| const ob = oauthBase(req); | |
| return { | |
| issuer: ob, | |
| authorization_endpoint: `${ob}/authorize`, | |
| token_endpoint: `${ob}/token`, | |
| token_endpoint_auth_methods_supported: ["client_secret_basic", "client_secret_post"], | |
| response_types_supported: ["code"], | |
| grant_types_supported: ["authorization_code", "refresh_token"], | |
| scopes_supported: ["mcp", "offline_access", "openid", "email"], | |
| code_challenge_methods_supported: ["S256", "plain"], | |
| }; | |
| } | |
| function protectedResourceMetadata(req) { | |
| const b = absBase(req); | |
| const resource = `${b}/sse`; | |
| const as = oauthBase(req); | |
| return { | |
| resource, | |
| authorization_servers: [as], | |
| scopes_supported: ["mcp", "offline_access", "openid", "email"], | |
| bearer_methods_supported: ["header"], | |
| }; | |
| } | |
| // ====== WELL-KNOWN (OAuth discovery) ====== | |
| // “どのパスから来ても” well-known を返す(/sse/token/.well-known/... 対策) | |
| app.get(/\/\.well-known\/oauth-authorization-server(\/.*)?$/, (req, res) => { | |
| res.json(oauthMetadata(req)); | |
| }); | |
| app.get(/\/\.well-known\/openid-configuration(\/.*)?$/, (req, res) => { | |
| res.json(oauthMetadata(req)); | |
| }); | |
| app.get(/\/\.well-known\/oauth-protected-resource(\/.*)?$/, (req, res) => { | |
| res.json(protectedResourceMetadata(req)); | |
| }); | |
| // ====== OAUTH AUTHORIZE/TOKEN ====== | |
| // NOTE: /authorize は疎通用(本番は必ずOIDC等に置換推奨) | |
| const codeStore = new Map(); // code -> { redirect_uri, code_challenge, code_challenge_method, createdAt } | |
| function issueCode() { | |
| return crypto.randomBytes(16).toString("hex"); | |
| } | |
| function base64Url(buf) { | |
| return Buffer.from(buf).toString("base64").replace(/\+/g, "-").replace(/\//g, "_").replace(/=+$/g, ""); | |
| } | |
| function sha256(str) { | |
| return crypto.createHash("sha256").update(str).digest(); | |
| } | |
| function verifyPkceIfPresent(stored, code_verifier) { | |
| if (!stored?.code_challenge) return true; | |
| if (!code_verifier) return false; | |
| const method = (stored.code_challenge_method || "plain").toString().toLowerCase(); | |
| if (method === "plain") return stored.code_challenge === code_verifier; | |
| const computed = base64Url(sha256(code_verifier)); | |
| return stored.code_challenge === computed; | |
| } | |
| function handleAuthorize(req, res) { | |
| const { | |
| response_type, | |
| client_id, | |
| redirect_uri, | |
| state, | |
| code_challenge, | |
| code_challenge_method, | |
| } = req.query; | |
| if (response_type !== "code") return res.status(400).send("unsupported response_type"); | |
| if (client_id !== CLIENT_ID) return res.status(400).send("invalid client_id"); | |
| if (!redirect_uri) return res.status(400).send("missing redirect_uri"); | |
| const code = issueCode(); | |
| codeStore.set(code, { | |
| redirect_uri: redirect_uri.toString(), | |
| code_challenge: code_challenge?.toString(), | |
| code_challenge_method: (code_challenge_method || "plain").toString(), | |
| createdAt: Date.now(), | |
| }); | |
| // 5分掃除 | |
| for (const [k, v] of codeStore.entries()) { | |
| if (Date.now() - v.createdAt > 5 * 60 * 1000) codeStore.delete(k); | |
| } | |
| const u = new URL(redirect_uri.toString()); | |
| u.searchParams.set("code", code); | |
| if (state) u.searchParams.set("state", state.toString()); | |
| return res.redirect(u.toString()); | |
| } | |
| app.get("/authorize", handleAuthorize); | |
| app.get("/sse/authorize", handleAuthorize); | |
| function parseBasic(req) { | |
| const auth = req.headers.authorization || ""; | |
| if (!auth.startsWith("Basic ")) return null; | |
| const decoded = Buffer.from(auth.slice(6), "base64").toString(); | |
| const idx = decoded.indexOf(":"); | |
| if (idx < 0) return null; | |
| return { id: decoded.slice(0, idx), secret: decoded.slice(idx + 1) }; | |
| } | |
| function readClientCreds(req) { | |
| const basic = parseBasic(req); | |
| if (basic) return { method: "basic", id: basic.id, secret: basic.secret }; | |
| const id = (req.body?.client_id || "").toString(); | |
| const secret = (req.body?.client_secret || "").toString(); | |
| if (id || secret) return { method: "post", id, secret }; | |
| return { method: "none", id: "", secret: "" }; | |
| } | |
| async function mintAccessToken(req, aud) { | |
| const iss = oauthBase(req); | |
| const now = Math.floor(Date.now() / 1000); | |
| return new SignJWT({ | |
| iss, | |
| aud, | |
| sub: "chatgpt", | |
| scope: "mcp offline_access openid email", | |
| iat: now, | |
| }) | |
| .setProtectedHeader({ alg: "HS256" }) | |
| .setIssuedAt() | |
| .setExpirationTime("15m") | |
| .sign(JWT_SECRET); | |
| } | |
| async function mintRefreshToken(req, aud) { | |
| const iss = oauthBase(req); | |
| return new SignJWT({ | |
| iss, | |
| aud, | |
| sub: "chatgpt", | |
| scope: "mcp offline_access openid email", | |
| type: "refresh", | |
| }) | |
| .setProtectedHeader({ alg: "HS256" }) | |
| .setIssuedAt() | |
| .setExpirationTime("30d") | |
| .sign(JWT_SECRET); | |
| } | |
| async function mintIdToken(req) { | |
| const iss = oauthBase(req); | |
| return new SignJWT({ | |
| iss, | |
| aud: CLIENT_ID, | |
| sub: "chatgpt-user", | |
| email: "chatgpt@local", | |
| email_verified: true, | |
| }) | |
| .setProtectedHeader({ alg: "HS256" }) | |
| .setIssuedAt() | |
| .setExpirationTime("15m") | |
| .sign(JWT_SECRET); | |
| } | |
| async function handleToken(req, res) { | |
| res.setHeader("Cache-Control", "no-store"); | |
| res.setHeader("Pragma", "no-cache"); | |
| const creds = readClientCreds(req); | |
| if (creds.id !== CLIENT_ID || creds.secret !== CLIENT_SECRET) { | |
| return res.status(401).send("invalid_client"); | |
| } | |
| const grantType = (req.body?.grant_type || "authorization_code").toString(); | |
| const resource = (req.body?.resource || "").toString(); | |
| const aud = resource || `${absBase(req)}/sse`; | |
| if (grantType === "refresh_token") { | |
| const access_token = await mintAccessToken(req, aud); | |
| return res.json({ | |
| access_token, | |
| token_type: "Bearer", | |
| expires_in: 900, | |
| scope: "mcp offline_access openid email", | |
| }); | |
| } | |
| const code = (req.body?.code || "").toString(); | |
| const redirect_uri = (req.body?.redirect_uri || "").toString(); | |
| const code_verifier = (req.body?.code_verifier || "").toString(); | |
| const stored = codeStore.get(code); | |
| if (stored?.redirect_uri && redirect_uri && stored.redirect_uri !== redirect_uri) { | |
| return res.status(400).send("redirect_uri mismatch"); | |
| } | |
| if (stored && stored.code_challenge) { | |
| if (!verifyPkceIfPresent(stored, code_verifier)) { | |
| return res.status(400).send("pkce verification failed"); | |
| } | |
| } | |
| if (stored) codeStore.delete(code); | |
| const access_token = await mintAccessToken(req, aud); | |
| const refresh_token = await mintRefreshToken(req, aud); | |
| const id_token = await mintIdToken(req); | |
| return res.json({ | |
| access_token, | |
| refresh_token, | |
| id_token, | |
| token_type: "Bearer", | |
| expires_in: 900, | |
| scope: "mcp offline_access openid email", | |
| }); | |
| } | |
| app.post("/token", handleToken); | |
| app.post("/sse/token", handleToken); | |
| // ====== BEARER for MCP ====== | |
| async function requireBearer(req, res, next) { | |
| const h = req.headers.authorization || ""; | |
| if (!h.startsWith("Bearer ")) return res.status(401).send("missing bearer"); | |
| try { | |
| await jwtVerify(h.slice(7), JWT_SECRET, { clockTolerance: "5s" }); | |
| next(); | |
| } catch { | |
| return res.status(401).send("invalid token"); | |
| } | |
| } | |
| // ====== MCP (Streamable HTTP) ====== | |
| const sessions = new Map(); // sid -> { transport, mcp } | |
| const bearerToSid = new Map(); // "Bearer xxx" -> sid (フォールバック用) | |
| // セッションIDをリクエストヘッダーに早期注入(フォールバック対策) | |
| async function injectSessionId(req, res, next) { | |
| const sidHeader = req.headers["mcp-session-id"]; | |
| if (!sidHeader) { | |
| const bearer = req.headers.authorization || ""; | |
| const mappedSid = bearerToSid.get(bearer); | |
| if (mappedSid && sessions.has(mappedSid)) { | |
| req.headers["mcp-session-id"] = mappedSid; | |
| console.log(`[MCP] injected session id: ${mappedSid}`); | |
| } | |
| } | |
| next(); | |
| } | |
| function createMcpServer() { | |
| const mcp = new McpServer({ name: "backlog-mcp", version: "1.0.0" }); | |
| if (!backlogClient) { | |
| // Backlog APIが設定されていない場合は基本ツールのみ | |
| mcp.registerTool( | |
| "ping", | |
| { | |
| title: "Ping", | |
| description: "疎通確認(pong)", | |
| inputSchema: z.object({}), | |
| }, | |
| async () => ({ content: [{ type: "text", text: "pong - Backlog API is not configured" }] }) | |
| ); | |
| return mcp; | |
| } | |
| // ===== SPACE TOOLSET ===== | |
| mcp.registerTool( | |
| "get_space", | |
| { | |
| title: "Get Space Information", | |
| description: "Backlogスペースの情報を取得します", | |
| inputSchema: z.object({}), | |
| }, | |
| async () => { | |
| try { | |
| const space = await backlogClient.getSpace(); | |
| return { content: [{ type: "text", text: JSON.stringify(space, null, 2) }] }; | |
| } catch (error) { | |
| return { content: [{ type: "text", text: `Error: ${error.message}` }], isError: true }; | |
| } | |
| } | |
| ); | |
| mcp.registerTool( | |
| "get_users", | |
| { | |
| title: "Get Users", | |
| description: "Backlogスペースのユーザー一覧を取得します", | |
| inputSchema: z.object({}), | |
| }, | |
| async () => { | |
| try { | |
| const users = await backlogClient.getUsers(); | |
| return { content: [{ type: "text", text: JSON.stringify(users, null, 2) }] }; | |
| } catch (error) { | |
| return { content: [{ type: "text", text: `Error: ${error.message}` }], isError: true }; | |
| } | |
| } | |
| ); | |
| mcp.registerTool( | |
| "get_myself", | |
| { | |
| title: "Get My User Information", | |
| description: "認証済みユーザーの情報を取得します", | |
| inputSchema: z.object({}), | |
| }, | |
| async () => { | |
| try { | |
| const user = await backlogClient.getMyself(); | |
| return { content: [{ type: "text", text: JSON.stringify(user, null, 2) }] }; | |
| } catch (error) { | |
| return { content: [{ type: "text", text: `Error: ${error.message}` }], isError: true }; | |
| } | |
| } | |
| ); | |
| // ===== PROJECT TOOLSET ===== | |
| mcp.registerTool( | |
| "get_project_list", | |
| { | |
| title: "Get Project List", | |
| description: "プロジェクト一覧を取得します", | |
| inputSchema: z.object({ | |
| archived: z.boolean().optional().describe("アーカイブされたプロジェクトを含めるかどうか"), | |
| all: z.boolean().optional().describe("すべてのプロジェクトを取得するかどうか"), | |
| }), | |
| }, | |
| async ({ archived, all }) => { | |
| try { | |
| const params = {}; | |
| if (archived !== undefined) params.archived = archived; | |
| if (all !== undefined) params.all = all; | |
| const projects = await backlogClient.getProjects(params); | |
| return { content: [{ type: "text", text: JSON.stringify(projects, null, 2) }] }; | |
| } catch (error) { | |
| return { content: [{ type: "text", text: `Error: ${error.message}` }], isError: true }; | |
| } | |
| } | |
| ); | |
| mcp.registerTool( | |
| "get_project", | |
| { | |
| title: "Get Project", | |
| description: "特定のプロジェクトの詳細情報を取得します", | |
| inputSchema: z.object({ | |
| projectIdOrKey: z.string().describe("プロジェクトIDまたはプロジェクトキー"), | |
| }), | |
| }, | |
| async ({ projectIdOrKey }) => { | |
| try { | |
| const project = await backlogClient.getProject(projectIdOrKey); | |
| return { content: [{ type: "text", text: JSON.stringify(project, null, 2) }] }; | |
| } catch (error) { | |
| return { content: [{ type: "text", text: `Error: ${error.message}` }], isError: true }; | |
| } | |
| } | |
| ); | |
| // ===== ISSUE TOOLSET ===== | |
| mcp.registerTool( | |
| "get_issues", | |
| { | |
| title: "Get Issues", | |
| description: "課題一覧を取得します", | |
| inputSchema: z.object({ | |
| projectId: z.array(z.number()).optional().describe("プロジェクトID"), | |
| issueTypeId: z.array(z.number()).optional().describe("課題種別ID"), | |
| categoryId: z.array(z.number()).optional().describe("カテゴリーID"), | |
| statusId: z.array(z.number()).optional().describe("状態ID (1:未対応, 2:処理中, 3:処理済み, 4:完了)"), | |
| priorityId: z.array(z.number()).optional().describe("優先度ID (2:高, 3:中, 4:低)"), | |
| assigneeId: z.array(z.number()).optional().describe("担当者ID"), | |
| createdUserId: z.array(z.number()).optional().describe("登録者ID"), | |
| count: z.number().optional().describe("取得件数 (デフォルト: 20, 最大: 100)"), | |
| offset: z.number().optional().describe("オフセット"), | |
| }), | |
| }, | |
| async (params) => { | |
| try { | |
| const issues = await backlogClient.getIssues(params); | |
| return { content: [{ type: "text", text: JSON.stringify(issues, null, 2) }] }; | |
| } catch (error) { | |
| return { content: [{ type: "text", text: `Error: ${error.message}` }], isError: true }; | |
| } | |
| } | |
| ); | |
| mcp.registerTool( | |
| "get_issue", | |
| { | |
| title: "Get Issue", | |
| description: "特定の課題の詳細情報を取得します", | |
| inputSchema: z.object({ | |
| issueIdOrKey: z.string().describe("課題IDまたは課題キー (例: PROJECT-123)"), | |
| }), | |
| }, | |
| async ({ issueIdOrKey }) => { | |
| try { | |
| const issue = await backlogClient.getIssue(issueIdOrKey); | |
| return { content: [{ type: "text", text: JSON.stringify(issue, null, 2) }] }; | |
| } catch (error) { | |
| return { content: [{ type: "text", text: `Error: ${error.message}` }], isError: true }; | |
| } | |
| } | |
| ); | |
| mcp.registerTool( | |
| "add_issue", | |
| { | |
| title: "Add Issue", | |
| description: "新しい課題を作成します", | |
| inputSchema: z.object({ | |
| projectId: z.number().describe("プロジェクトID"), | |
| summary: z.string().describe("課題の件名"), | |
| issueTypeId: z.number().describe("課題種別ID"), | |
| priorityId: z.number().describe("優先度ID (2:高, 3:中, 4:低)"), | |
| description: z.string().optional().describe("課題の詳細"), | |
| assigneeId: z.number().optional().describe("担当者ID"), | |
| categoryId: z.array(z.number()).optional().describe("カテゴリーID"), | |
| }), | |
| }, | |
| async (params) => { | |
| try { | |
| const issue = await backlogClient.postIssue(params); | |
| return { content: [{ type: "text", text: JSON.stringify(issue, null, 2) }] }; | |
| } catch (error) { | |
| return { content: [{ type: "text", text: `Error: ${error.message}` }], isError: true }; | |
| } | |
| } | |
| ); | |
| mcp.registerTool( | |
| "update_issue", | |
| { | |
| title: "Update Issue", | |
| description: "既存の課題を更新します", | |
| inputSchema: z.object({ | |
| issueIdOrKey: z.string().describe("課題IDまたは課題キー"), | |
| summary: z.string().optional().describe("課題の件名"), | |
| description: z.string().optional().describe("課題の詳細"), | |
| statusId: z.number().optional().describe("状態ID"), | |
| priorityId: z.number().optional().describe("優先度ID"), | |
| assigneeId: z.number().optional().describe("担当者ID"), | |
| comment: z.string().optional().describe("コメント"), | |
| }), | |
| }, | |
| async ({ issueIdOrKey, ...params }) => { | |
| try { | |
| const issue = await backlogClient.patchIssue(issueIdOrKey, params); | |
| return { content: [{ type: "text", text: JSON.stringify(issue, null, 2) }] }; | |
| } catch (error) { | |
| return { content: [{ type: "text", text: `Error: ${error.message}` }], isError: true }; | |
| } | |
| } | |
| ); | |
| mcp.registerTool( | |
| "get_issue_comments", | |
| { | |
| title: "Get Issue Comments", | |
| description: "課題のコメント一覧を取得します", | |
| inputSchema: z.object({ | |
| issueIdOrKey: z.string().describe("課題IDまたは課題キー"), | |
| count: z.number().optional().describe("取得件数"), | |
| offset: z.number().optional().describe("オフセット"), | |
| }), | |
| }, | |
| async ({ issueIdOrKey, count, offset }) => { | |
| try { | |
| const params = {}; | |
| if (count) params.count = count; | |
| if (offset) params.offset = offset; | |
| const comments = await backlogClient.getIssueComments(issueIdOrKey, params); | |
| return { content: [{ type: "text", text: JSON.stringify(comments, null, 2) }] }; | |
| } catch (error) { | |
| return { content: [{ type: "text", text: `Error: ${error.message}` }], isError: true }; | |
| } | |
| } | |
| ); | |
| mcp.registerTool( | |
| "add_issue_comment", | |
| { | |
| title: "Add Issue Comment", | |
| description: "課題にコメントを追加します", | |
| inputSchema: z.object({ | |
| issueIdOrKey: z.string().describe("課題IDまたは課題キー"), | |
| content: z.string().describe("コメント内容"), | |
| }), | |
| }, | |
| async ({ issueIdOrKey, content }) => { | |
| try { | |
| const comment = await backlogClient.postIssueComment(issueIdOrKey, { content }); | |
| return { content: [{ type: "text", text: JSON.stringify(comment, null, 2) }] }; | |
| } catch (error) { | |
| return { content: [{ type: "text", text: `Error: ${error.message}` }], isError: true }; | |
| } | |
| } | |
| ); | |
| // ===== WIKI TOOLSET ===== | |
| mcp.registerTool( | |
| "get_wiki_pages", | |
| { | |
| title: "Get Wiki Pages", | |
| description: "Wikiページ一覧を取得します", | |
| inputSchema: z.object({ | |
| projectIdOrKey: z.string().describe("プロジェクトIDまたはプロジェクトキー"), | |
| }), | |
| }, | |
| async ({ projectIdOrKey }) => { | |
| try { | |
| const wikis = await backlogClient.getWikis({ projectIdOrKey }); | |
| return { content: [{ type: "text", text: JSON.stringify(wikis, null, 2) }] }; | |
| } catch (error) { | |
| return { content: [{ type: "text", text: `Error: ${error.message}` }], isError: true }; | |
| } | |
| } | |
| ); | |
| mcp.registerTool( | |
| "get_wiki", | |
| { | |
| title: "Get Wiki", | |
| description: "特定のWikiページの詳細情報を取得します", | |
| inputSchema: z.object({ | |
| wikiId: z.number().describe("WikiページID"), | |
| }), | |
| }, | |
| async ({ wikiId }) => { | |
| try { | |
| const wiki = await backlogClient.getWiki(wikiId); | |
| return { content: [{ type: "text", text: JSON.stringify(wiki, null, 2) }] }; | |
| } catch (error) { | |
| return { content: [{ type: "text", text: `Error: ${error.message}` }], isError: true }; | |
| } | |
| } | |
| ); | |
| // ===== GIT TOOLSET ===== | |
| mcp.registerTool( | |
| "get_git_repositories", | |
| { | |
| title: "Get Git Repositories", | |
| description: "プロジェクトのGitリポジトリ一覧を取得します", | |
| inputSchema: z.object({ | |
| projectIdOrKey: z.string().describe("プロジェクトIDまたはプロジェクトキー"), | |
| }), | |
| }, | |
| async ({ projectIdOrKey }) => { | |
| try { | |
| const repos = await backlogClient.getGitRepositories(projectIdOrKey); | |
| return { content: [{ type: "text", text: JSON.stringify(repos, null, 2) }] }; | |
| } catch (error) { | |
| return { content: [{ type: "text", text: `Error: ${error.message}` }], isError: true }; | |
| } | |
| } | |
| ); | |
| mcp.registerTool( | |
| "get_pull_requests", | |
| { | |
| title: "Get Pull Requests", | |
| description: "プルリクエスト一覧を取得します", | |
| inputSchema: z.object({ | |
| projectIdOrKey: z.string().describe("プロジェクトIDまたはプロジェクトキー"), | |
| repoIdOrName: z.string().describe("リポジトリIDまたは名前"), | |
| statusId: z.array(z.number()).optional().describe("状態ID (1:オープン, 2:クローズ, 3:マージ済み)"), | |
| count: z.number().optional().describe("取得件数"), | |
| offset: z.number().optional().describe("オフセット"), | |
| }), | |
| }, | |
| async ({ projectIdOrKey, repoIdOrName, ...params }) => { | |
| try { | |
| const pullRequests = await backlogClient.getPullRequests(projectIdOrKey, repoIdOrName, params); | |
| return { content: [{ type: "text", text: JSON.stringify(pullRequests, null, 2) }] }; | |
| } catch (error) { | |
| return { content: [{ type: "text", text: `Error: ${error.message}` }], isError: true }; | |
| } | |
| } | |
| ); | |
| mcp.registerTool( | |
| "get_pull_request", | |
| { | |
| title: "Get Pull Request", | |
| description: "特定のプルリクエストの詳細情報を取得します", | |
| inputSchema: z.object({ | |
| projectIdOrKey: z.string().describe("プロジェクトIDまたはプロジェクトキー"), | |
| repoIdOrName: z.string().describe("リポジトリIDまたは名前"), | |
| number: z.number().describe("プルリクエスト番号"), | |
| }), | |
| }, | |
| async ({ projectIdOrKey, repoIdOrName, number }) => { | |
| try { | |
| const pullRequest = await backlogClient.getPullRequest(projectIdOrKey, repoIdOrName, number); | |
| return { content: [{ type: "text", text: JSON.stringify(pullRequest, null, 2) }] }; | |
| } catch (error) { | |
| return { content: [{ type: "text", text: `Error: ${error.message}` }], isError: true }; | |
| } | |
| } | |
| ); | |
| // ===== NOTIFICATIONS TOOLSET ===== | |
| mcp.registerTool( | |
| "get_notifications", | |
| { | |
| title: "Get Notifications", | |
| description: "通知一覧を取得します", | |
| inputSchema: z.object({ | |
| count: z.number().optional().describe("取得件数 (デフォルト: 20, 最大: 100)"), | |
| offset: z.number().optional().describe("オフセット"), | |
| }), | |
| }, | |
| async (params) => { | |
| try { | |
| const notifications = await backlogClient.getNotifications(params); | |
| return { content: [{ type: "text", text: JSON.stringify(notifications, null, 2) }] }; | |
| } catch (error) { | |
| return { content: [{ type: "text", text: `Error: ${error.message}` }], isError: true }; | |
| } | |
| } | |
| ); | |
| mcp.registerTool( | |
| "get_notifications_count", | |
| { | |
| title: "Get Notifications Count", | |
| description: "未読通知数を取得します", | |
| inputSchema: z.object({}), | |
| }, | |
| async () => { | |
| try { | |
| const count = await backlogClient.getNotificationCount(); | |
| return { content: [{ type: "text", text: JSON.stringify(count, null, 2) }] }; | |
| } catch (error) { | |
| return { content: [{ type: "text", text: `Error: ${error.message}` }], isError: true }; | |
| } | |
| } | |
| ); | |
| // Ping tool | |
| mcp.registerTool( | |
| "ping", | |
| { | |
| title: "Ping", | |
| description: "疎通確認(pong)", | |
| inputSchema: z.object({}), | |
| }, | |
| async () => ({ content: [{ type: "text", text: "pong" }] }) | |
| ); | |
| return mcp; | |
| } | |
| function exposeSessionHeaders(res) { | |
| // クライアントが session header を読めるように | |
| res.setHeader("Access-Control-Expose-Headers", "MCP-Session-Id, mcp-session-id"); | |
| } | |
| async function getOrCreateTransport(req, res) { | |
| const sidHeader = req.headers["mcp-session-id"]?.toString(); | |
| const bearer = (req.headers.authorization || "").toString(); | |
| // 1) ヘッダに sid があるならそれを優先(injectSessionIdで既に設定済みの可能性あり) | |
| if (sidHeader && sessions.has(sidHeader)) { | |
| exposeSessionHeaders(res); | |
| res.setHeader("MCP-Session-Id", sidHeader); | |
| console.log(`[MCP] using existing session sid=${sidHeader}`); | |
| return { transport: sessions.get(sidHeader).transport, newSession: false }; | |
| } | |
| // 2) initialize のときだけ新規作成 | |
| if (isInitializeRequest(req.body)) { | |
| const mcp = createMcpServer(); | |
| const newSid = crypto.randomUUID(); | |
| let transport; | |
| transport = new StreamableHTTPServerTransport({ | |
| sessionIdGenerator: () => newSid, | |
| onsessioninitialized: (sid) => { | |
| sessions.set(sid, { transport, mcp }); | |
| bearerToSid.set(bearer, sid); | |
| console.log(`[MCP] session initialized sid=${sid}`); | |
| }, | |
| }); | |
| transport.onclose = () => { | |
| if (transport.sessionId && sessions.has(transport.sessionId)) { | |
| sessions.delete(transport.sessionId); | |
| // bearerToSid は上書き運用なので消さなくても良いが、閉じたら外す | |
| for (const [k, v] of bearerToSid.entries()) { | |
| if (v === transport.sessionId) bearerToSid.delete(k); | |
| } | |
| console.log(`[MCP] session closed sid=${transport.sessionId}`); | |
| } | |
| }; | |
| await mcp.connect(transport); | |
| await new Promise(resolve => setTimeout(resolve, 10)); | |
| exposeSessionHeaders(res); | |
| res.setHeader("MCP-Session-Id", newSid); | |
| return { transport, newSession: true, sessionId: newSid }; | |
| } | |
| console.log(`[MCP] ERROR: no valid session found. sidHeader=${sidHeader}, isInit=${isInitializeRequest(req.body)}, body=${JSON.stringify(req.body)}`); | |
| return null; | |
| } | |
| // POST: initialize / tool calls | |
| app.post("/sse", requireBearer, injectSessionId, async (req, res) => { | |
| const sidHeader = req.headers["mcp-session-id"]; | |
| const bearer = req.headers.authorization || ""; | |
| // 2回目のinitializeリクエストを検出(クライアントがセッションIDを認識していない場合) | |
| if (isInitializeRequest(req.body) && sidHeader && sessions.has(sidHeader)) { | |
| console.log(`[MCP] POST /sse: Re-initialize request detected for existing session ${sidHeader}`); | |
| // 既存セッションを削除して新しいセッションを作成 | |
| const oldSession = sessions.get(sidHeader); | |
| if (oldSession.transport.onclose) { | |
| try { oldSession.transport.onclose(); } catch (e) {} | |
| } | |
| sessions.delete(sidHeader); | |
| bearerToSid.delete(bearer); | |
| // ヘッダーから削除して新規作成を促す | |
| delete req.headers["mcp-session-id"]; | |
| } | |
| const result = await getOrCreateTransport(req, res); | |
| if (!result) { | |
| exposeSessionHeaders(res); | |
| console.log(`[MCP] POST /sse: returning 400 - no valid transport`); | |
| return res.status(400).json({ | |
| jsonrpc: "2.0", | |
| error: { code: -32000, message: "Invalid or missing session" }, | |
| id: req.body?.id || null, | |
| }); | |
| } | |
| const { transport, newSession, sessionId } = result; | |
| const sid = req.headers["mcp-session-id"] || sessionId; | |
| console.log(`[MCP] POST /sse: calling transport.handleRequest with sid=${sid}${newSession ? ' (new)' : ''}`); | |
| await transport.handleRequest(req, res, req.body); | |
| }); | |
| // GET: server->client stream | |
| app.get("/sse", requireBearer, injectSessionId, async (req, res) => { | |
| const sid = req.headers["mcp-session-id"]?.toString(); | |
| if (!sid || !sessions.has(sid)) { | |
| console.log(`[MCP] GET /sse: no valid session. sid=${sid}`); | |
| return res.status(400).send("Invalid or missing session"); | |
| } | |
| exposeSessionHeaders(res); | |
| res.setHeader("MCP-Session-Id", sid); | |
| console.log(`[MCP] GET /sse using sid=${sid}`); | |
| await sessions.get(sid).transport.handleRequest(req, res); | |
| }); | |
| // DELETE: end session | |
| app.delete("/sse", requireBearer, async (req, res) => { | |
| const sid = req.headers["mcp-session-id"]?.toString(); | |
| if (!sid || !sessions.has(sid)) { | |
| console.log(`[MCP] DELETE /sse: invalid session. sid=${sid}`); | |
| return res.status(400).send("Invalid or missing session"); | |
| } | |
| exposeSessionHeaders(res); | |
| res.setHeader("MCP-Session-Id", sid); | |
| console.log(`[MCP] DELETE /sse for sid=${sid}`); | |
| await sessions.get(sid).transport.handleRequest(req, res); | |
| }); | |
| // Health | |
| app.get("/", (_req, res) => res.status(200).send("OK")); | |
| app.listen(PORT, "0.0.0.0", () => { | |
| console.log(`Listening on ${PORT}`); | |
| }); | |