get_code_sample
Retrieve code samples for NicePay API integration across multiple programming languages to implement payment processing features like payment window calls, authentication, and transaction approval.
Instructions
나이스페이 API 사용 예시 코드를 제공합니다. 언어별로 코드 샘플을 조회할 수 있습니다.
Input Schema
TableJSON Schema
| Name | Required | Description | Default |
|---|---|---|---|
| topic | Yes | 코드 샘플을 찾을 주제 (예: "결제창 호출", "Basic 인증", "결제 승인" 등) | |
| language | No | 언어 (선택사항, 예 "javascript", "python", "curl" 등) |
Implementation Reference
- src/index.ts:549-700 (handler)The primary handler function for the 'get_code_sample' tool. It searches indexed documents for relevant code blocks matching the provided topic and optional language, computes relevance scores, ranks them, and formats up to 5 top code samples with source information for return.private async getCodeSample(topic: string, language?: string) { if (!topic || topic.trim().length === 0) { return { content: [ { type: 'text', text: '주제를 입력해주세요.', }, ], isError: true, }; } try { const query = topic.trim(); // 1. 관련 문서 검색 const searchResults = this.docIndexer.searchDocuments(query); if (searchResults.length === 0) { return { content: [ { type: 'text', text: `"${query}"에 대한 코드 샘플을 찾을 수 없습니다.\n\n다른 키워드로 검색해보세요.`, }, ], }; } // 2. 각 문서에서 코드 블록 추출 const codeBlocks: Array<{ doc: any; block: any; relevance: number; }> = []; for (const doc of searchResults.slice(0, 10)) { let blocks = language ? MarkdownParser.extractCodeBlocksByLanguage(doc.content, language) : MarkdownParser.extractCodeBlocks(doc.content); // 주제와 관련성 계산 blocks.forEach(block => { const blockText = block.code.toLowerCase(); const queryLower = query.toLowerCase(); let relevance = 0; // 코드 내용에 주제 키워드가 포함되어 있는지 if (blockText.includes(queryLower)) { relevance += 10; } // 언어 매칭 (언어가 지정된 경우) if (language && block.language) { const blockLang = block.language.toLowerCase(); const targetLang = language.toLowerCase(); if (blockLang === targetLang || blockLang.includes(targetLang) || targetLang.includes(blockLang)) { relevance += 5; } } // API 관련 키워드 체크 const apiKeywords = ['nicepay', 'api', 'request', 'pay', 'payment', 'curl', 'fetch', 'axios', 'http']; if (apiKeywords.some(keyword => blockText.includes(keyword))) { relevance += 3; } if (relevance > 0 || blocks.length === 1) { codeBlocks.push({ doc, block, relevance, }); } }); } // 관련성 순으로 정렬 codeBlocks.sort((a, b) => b.relevance - a.relevance); if (codeBlocks.length === 0) { return { content: [ { type: 'text', text: `"${query}"${language ? ` (${language})` : ''}에 대한 코드 샘플을 찾을 수 없습니다.\n\n다른 키워드나 언어로 검색해보세요.`, }, ], }; } // 3. 결과 포맷팅 let resultText = `## "${query}" 코드 샘플${language ? ` (${language})` : ''}\n\n`; resultText += `총 ${codeBlocks.length}개의 코드 샘플을 찾았습니다.\n\n`; resultText += `---\n\n`; // 최대 5개만 표시 const limitedBlocks = codeBlocks.slice(0, 5); limitedBlocks.forEach((item, index) => { resultText += `### ${index + 1}. ${item.doc.title}\n\n`; resultText += `📄 출처: ${item.doc.filePath}\n\n`; if (item.block.language) { resultText += `**언어:** ${item.block.language}\n\n`; } resultText += `\`\`\`${item.block.language || ''}\n${item.block.code}\n\`\`\`\n\n`; // 코드 블록 근처의 설명 찾기 (섹션 내용에서) const section = item.doc.sections.find((s: any) => { const sectionContent = s.content.toLowerCase(); return sectionContent.includes(item.block.code.substring(0, 50).toLowerCase()); }); if (section) { const description = section.content.substring(0, 200).trim(); if (description && !description.toLowerCase().includes(item.block.code.substring(0, 30).toLowerCase())) { resultText += `**설명:** ${description}...\n\n`; } } resultText += `---\n\n`; }); if (codeBlocks.length > 5) { resultText += `\n*총 ${codeBlocks.length}개 중 상위 5개만 표시됩니다.*\n`; } return { content: [ { type: 'text', text: resultText, }, ], }; } catch (error) { const errorMessage = error instanceof Error ? error.message : String(error); logger.error(`코드 샘플 조회 오류 (topic: ${topic}):`, errorMessage); return { content: [ { type: 'text', text: `코드 샘플 조회 중 오류가 발생했습니다. 다시 시도해주세요.`, }, ], isError: true, }; } }
- src/index.ts:77-90 (schema)Input schema definition for the 'get_code_sample' tool, specifying 'topic' as required string and optional 'language' string.inputSchema: { type: 'object', properties: { topic: { type: 'string', description: '코드 샘플을 찾을 주제 (예: "결제창 호출", "Basic 인증", "결제 승인" 등)', }, language: { type: 'string', description: '언어 (선택사항, 예 "javascript", "python", "curl" 등)', }, }, required: ['topic'], },
- src/index.ts:74-91 (registration)Tool registration in the ListTools response, defining name, description, and input schema.{ name: 'get_code_sample', description: '나이스페이 API 사용 예시 코드를 제공합니다. 언어별로 코드 샘플을 조회할 수 있습니다.', inputSchema: { type: 'object', properties: { topic: { type: 'string', description: '코드 샘플을 찾을 주제 (예: "결제창 호출", "Basic 인증", "결제 승인" 등)', }, language: { type: 'string', description: '언어 (선택사항, 예 "javascript", "python", "curl" 등)', }, }, required: ['topic'], }, },
- src/index.ts:151-168 (registration)Dispatch handler in CallToolRequestSchema that validates parameters and invokes the getCodeSample method.case 'get_code_sample': if (!args?.topic || typeof args.topic !== 'string') { logger.warn(`잘못된 파라미터: get_code_sample`, args); return { content: [ { type: 'text', text: 'topic 파라미터가 필요합니다.', }, ], isError: true, }; } result = await this.getCodeSample( args.topic, args.language as string | undefined, ); break;