# Gemini + MCP 데모 스크립트 v3: Gemini SDK 기능 탐색 ## Gemini SDK란? Google은 공식 TypeScript/JavaScript SDK인 `@google/genai`를 제공한다. 이 SDK는: - Gemini Developer API 지원 - Vertex AI 지원 - TypeScript 네이티브 지원 - 2025년 4월에 최신 버전 릴리즈 ## Function Calling 지원 확인 좋은 소식: **Gemini SDK는 function calling을 완벽하게 지원한다!** ### 기본 구조 ```typescript import { GoogleGenAI, FunctionDeclaration } from '@google/genai'; const ai = new GoogleGenAI({ apiKey: GEMINI_API_KEY }); const response = await ai.models.generateContent({ model: 'gemini-2.0-flash-001', contents: 'What is the weather in Boston?', config: { tools: [{ functionDeclarations: [ { name: 'get_weather', description: 'Get the current weather in a given location', parameters: { type: 'object', properties: { location: { type: 'string', description: 'The city and state, e.g. San Francisco, CA' }, unit: { type: 'string', enum: ['celsius', 'fahrenheit'] } }, required: ['location'] } } ] }] } }); // Check if model wants to call a function if (response.functionCalls) { console.log('Function calls:', response.functionCalls); } ``` ## 핵심 개념 ### 1. Function Declaration Tool의 정의를 나타낸다: ```typescript interface FunctionDeclaration { name: string; description?: string; parametersJsonSchema?: { type: 'object'; properties: Record; required?: string[]; }; } ``` **중요**: Gemini는 **JSON Schema** 형식으로 파라미터를 정의한다. ### 2. Tool Interface Gemini의 `Tool` 인터페이스는 다양한 기능을 지원한다: ```typescript interface Tool { // Custom function calling functionDeclarations?: FunctionDeclaration[]; // 사용자 정의 함수를 선언하는 리스트. 우리가 MCP 연동에 사용할 부분 // Code execution codeExecution?: ToolCodeExecution; // 모델이 생성 과정에서 코드를 직접 실행할 수 있게 함 // Python 코드 등을 실행하여 결과를 활용 가능 // Google Search googleSearch?: GoogleSearch; // Google Search로 구동되는 특화된 검색 도구 // 실시간 웹 정보 검색 // Google Search Retrieval googleSearchRetrieval?: GoogleSearchRetrieval; // Google Search 기반의 검색 retrieval 도구 // RAG(Retrieval-Augmented Generation) 패턴에 활용 // Google Maps googleMaps?: GoogleMaps; // Google Maps로 구동되는 특화된 도구 // 위치 정보, 경로 검색 등 // Enterprise Web Search enterpriseWebSearch?: EnterpriseWebSearch; // Vertex AI Search와 Sec4 컴플라이언스 기반 // 기업용 보안 웹 검색 도구 // Retrieval (RAG) retrieval?: Retrieval; // 외부 지식을 가져오기 위한 retrieval 도구 // 시스템이 항상 제공된 retrieval 도구를 실행하여 프롬프트에 답변 // RAG 패턴의 핵심 // URL Context urlContext?: UrlContext; // URL 컨텍스트 검색을 지원하는 도구 // 특정 URL의 내용을 가져와서 컨텍스트로 활용 } ``` **우리가 주목할 것은 `functionDeclarations`다.** ### 3. Function Calling Config Function calling 동작을 제어할 수 있다: ```typescript import { FunctionCallingConfigMode } from '@google/genai'; config: { toolConfig: { functionCallingConfig: { mode: FunctionCallingConfigMode.ANY, // 반드시 함수 호출 allowedFunctionNames: ['get_weather'] // 허용할 함수 제한 } } } ``` **Modes**: - `AUTO`: 모델이 자동 판단 (기본값) - `ANY`: 반드시 함수 중 하나 호출 - `NONE`: 함수 호출 비활성화 ### 4. CallableTool Interface 가장 흥미로운 발견: **CallableTool 인터페이스** ```typescript interface CallableTool { callTool(functionCalls: FunctionCall[]): Promise; tool(): Promise; } ``` 이 인터페이스는: - 외부 애플리케이션과 통합 가능 - **Model Context Protocol (MCP) 지원 명시** - 로컬 함수 또는 원격 도구 모두 지원 ## MCP 연동 가능성 분석 ### 공식 문서에서 발견한 것 > "Defines the structure of an invokable tool that can be executed with **external applications (e.g., via Model Context Protocol)** or local functions using function calling." **결론**: Gemini SDK는 공식적으로 MCP를 언급하고 있다! ### 연동 전략 Gemini SDK와 MCP를 연동하는 방법: ``` ┌──────────────┐ │ Gemini │ │ Model │ └──────┬───────┘ │ │ functionDeclarations │ ┌──────▼───────┐ │ Wrapper │ ◄── 우리가 작성할 코드 │ Function │ └──────┬───────┘ │ │ HTTP Request │ ┌──────▼───────┐ │ Vercel MCP │ │ Server │ └──────────────┘ ``` **핵심 아이디어**: 1. Vercel MCP server의 tool을 조회 2. 각 MCP tool을 Gemini의 `functionDeclaration`으로 변환 3. Gemini가 function을 호출하면 4. 우리의 wrapper 코드가 MCP server로 HTTP 요청 5. 결과를 Gemini에 반환 ## 실제 구현 가능성 ### 장점 1. **표준 준수**: JSON Schema 사용으로 MCP tool schema와 호환성 좋음 2. **공식 지원**: MCP가 공식 문서에 명시됨 3. **유연성**: HTTP transport로 어디서나 동작 4. **타입 안전성**: TypeScript 네이티브 지원 ### 고려사항 1. **수동 래핑**: MCP tool → Gemini function declaration 변환 필요 2. **에러 핸들링**: 네트워크 오류, MCP 서버 오류 처리 3. **인증**: Vercel API key 등 인증 관리 ## Live API에서의 Tool 사용 Gemini는 실시간 스트리밍 API에서도 tool 사용을 지원한다: ```typescript // Live server에서 tool 설정 types.LiveConnectConfig#tools // Function response 전송 sendFunctionResponse(...) ``` 이는 실시간 대화형 애플리케이션에서도 MCP를 활용할 수 있음을 의미한다. ## 다음 단계 v4에서는 이제 구체적인 기술 스택을 정하고, 어떻게 구현할지 설계할 것이다. **핵심 질문**: - Vercel MCP server의 HTTP endpoint는 어디인가? - MCP tool schema를 어떻게 Gemini function declaration으로 변환할까? - 멀티턴 대화에서 어떻게 상태를 관리할까? --- **작성일**: 2025-11-26 **참고**: - [Google Gen AI SDK Documentation](https://googleapis.github.io/js-genai/release_docs/) - [Gemini API Tools Guide](https://ai.google.dev/gemini-api/docs/tools)