getProjects
Retrieve project listings from Backlog to manage tasks and track issues through the MCP server interface.
Instructions
プロジェクト一覧の取得
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
No arguments | |||
Implementation Reference
- registerEndpoints.ts:60-151 (handler)The core handler logic for the getProjects tool (shared with other tools). It parses input with the tool's Zod schema, prepares the endpoint path 'projects', calls fetchFromBacklog, and returns the JSON stringified data.const handler = async (params: Record<string, unknown>): Promise<McpResponse> => { try { // パラメータのバリデーション const validatedParams = await endpoint.schema.parseAsync(params); // URL中のプレースホルダーを置換 let path = endpoint.path; // URIスキーム(例:space://info)の場合はBacklog APIのパスに変換 if (path.includes('://')) { // URIスキームを取り除いてAPIパスに変換 const uriParts = path.split('://'); const resourceType = uriParts[0]; const resourcePath = uriParts[1]; // リソースタイプに応じてAPIパスを構築 switch (resourceType) { case 'space': path = 'space'; break; case 'projects': if (resourcePath === 'list') { path = 'projects'; } else { path = `projects/${resourcePath}`; } break; case 'issues': if (resourcePath.includes('/list')) { const projectPart = resourcePath.split('/')[0]; path = 'issues'; validatedParams.projectIdOrKey = projectPart; } else if (resourcePath.includes('/details')) { const issuePart = resourcePath.split('/')[0]; path = `issues/${issuePart}`; } break; case 'wikis': if (resourcePath.includes('/list')) { const projectPart = resourcePath.split('/')[0]; path = 'wikis'; validatedParams.projectIdOrKey = projectPart; } break; case 'users': path = 'users'; break; default: path = resourcePath; } } // 通常のパスパラメータの置換処理 for (const [key, value] of Object.entries(validatedParams)) { if (typeof value === "string" || typeof value === "number") { const placeholder = `{${key}}`; if (path.includes(placeholder)) { path = path.replace(placeholder, String(value)); // プレースホルダーとして使用したパラメータは削除 delete validatedParams[key]; } } } // メソッドの追加 if (endpoint.method !== "GET") { validatedParams.method = endpoint.method; } // APIリクエストの実行 const data = await fetchFromBacklog(path, validatedParams); return { content: [{ type: "text" as const, text: JSON.stringify(data, null, 2) }], }; } catch (error: any) { // エラーメッセージの整形 const errorMessage = error.errors ? `バリデーションエラー: ${JSON.stringify(error.errors)}` : `エラー: ${error.message}`; return { content: [{ type: "text" as const, text: errorMessage }], isError: true, }; } };
- registerEndpoints.ts:156-160 (registration)The MCP server.tool() registration that binds the name 'getProjects', description, and generic handler function for execution.server.tool( endpoint.name, endpoint.description, async (args: Record<string, unknown>) => handler(args) );
- src/endpoints.ts:21-28 (registration)The BacklogEndpoint configuration object for 'getProjects', specifying name, description, API path ('projects'), method ('GET'), input schema (empty object), and type ('tool'). Serves as both registration data and schema definition.{ name: "getProjects", description: "プロジェクト一覧の取得", path: "projects", method: "GET", schema: z.object({}).strict(), type: "tool" },
- src/backlogApi.ts:32-167 (helper)The fetchFromBacklog utility function that performs the actual API call to https://{domain}/api/v2/projects for getProjects, managing URL construction, query/body params, authentication via apiKey, error handling, and JSON response processing.export async function fetchFromBacklog(endpoint: string, params: Record<string, any> = {}): Promise<any> { // 環境変数のバリデーション const domain = process.env.BACKLOG_DOMAIN; const apiKey = process.env.BACKLOG_API_KEY; if (!domain) { throw new Error('環境変数 BACKLOG_DOMAIN が設定されていません'); } if (!apiKey) { throw new Error('環境変数 BACKLOG_API_KEY が設定されていません'); } try { // パラメータのサニタイズ const sanitizedParams: Record<string, any> = {}; // projectIdOrKeyパラメータをprojectIdに変換(互換性のため) if (params.projectIdOrKey !== undefined) { sanitizedParams.projectId = params.projectIdOrKey; delete params.projectIdOrKey; } // その他のパラメータをコピー Object.keys(params).forEach(key => { if (params[key] !== undefined && params[key] !== null) { sanitizedParams[key] = params[key]; } }); // エンドポイントのパスパラメータを置換 let processedEndpoint = endpoint; const pathParams = processedEndpoint.match(/:([a-zA-Z0-9_]+)/g) || []; for (const param of pathParams) { const paramName = param.substring(1); // :を除去 if (sanitizedParams[paramName] === undefined) { throw new Error(`パスパラメータ ${paramName} が指定されていません`); } processedEndpoint = processedEndpoint.replace(param, sanitizedParams[paramName]); delete sanitizedParams[paramName]; } // リクエストURLの構築 const baseUrl = `https://${domain}/api/v2/${processedEndpoint}`; const isPost = processedEndpoint.includes('POST'); let url = baseUrl; let requestOptions: RequestInit = { headers: { 'Content-Type': 'application/json', }, }; // GETリクエストの場合はクエリパラメータを追加 if (!isPost) { const queryParams = new URLSearchParams(); queryParams.append('apiKey', apiKey); Object.keys(sanitizedParams).forEach(key => { if (Array.isArray(sanitizedParams[key])) { sanitizedParams[key].forEach((value: any) => { queryParams.append(`${key}[]`, value.toString()); }); } else { queryParams.append(key, sanitizedParams[key].toString()); } }); url = `${baseUrl}?${queryParams.toString()}`; } else { // POSTリクエストの場合はボディにパラメータを設定 requestOptions.method = 'POST'; requestOptions.body = JSON.stringify(sanitizedParams); url = `${baseUrl}?apiKey=${apiKey}`; } // デバッグ用ログ(開発時のみ) if (process.env.NODE_ENV === 'development') { console.debug(`Backlog API リクエスト: ${url}`); console.debug('パラメータ:', sanitizedParams); } // APIリクエストの実行 const response = await fetch(url, requestOptions); // レスポンスのステータスコードチェック if (!response.ok) { const errorText = await response.text(); let errorMessage = `Backlog API エラー: HTTP ${response.status}`; try { const errorJson = JSON.parse(errorText); if (isBacklogError(errorJson)) { const error = errorJson.errors[0]; errorMessage = `Backlog API呼び出しエラー: Backlogエラー [${error.code}]: ${error.message}${error.moreInfo ? ` - ${error.moreInfo}` : ''}`; } } catch (e) { errorMessage += ` - ${errorText}`; } throw new Error(errorMessage); } // レスポンスのJSONパース try { const data = await response.json(); // Backlogエラーのチェックとエラーメッセージのフォーマット if (isBacklogError(data)) { const error = data.errors[0]; throw new Error(`Backlog API呼び出しエラー: Backlogエラー [${error.code}]: ${error.message}${error.moreInfo ? ` - ${error.moreInfo}` : ''}`); } return data; } catch (error) { if (error instanceof SyntaxError) { throw new Error(`Backlog API呼び出しエラー: JSONパースエラー - ${error.message}`); } throw error; } } catch (error) { // ネットワークエラーなどの例外処理 if (error instanceof TypeError && error.message.includes('fetch')) { throw new Error(`Backlog API接続エラー: ${error.message}`); } // タイムアウトエラー if (error instanceof Error && error.name === 'AbortError') { throw new Error('Backlog APIタイムアウトエラー: リクエストがタイムアウトしました'); } // その他のエラーはそのまま再スロー throw error; }
- server.ts:29-29 (registration)Top-level call to registerEndpoints(server), which iterates over endpoints and registers the getProjects tool among others.registerEndpoints(server);