TypeScript

Module
Practical Implementation
Progress
33%

Sample

This is a Typescript sample for an MCP Server

Here's a tool creation example:


this.mcpServer.tool(

'completion',

{

    model: z.string(),

    prompt: z.string(),

    options: z.object({

        temperature: z.number().optional(),

        max_tokens: z.number().optional(),

        stream: z.boolean().optional()

    }).optional()

},

async ({ model, prompt, options }) => {

    console.log(`Processing completion request for model: ${model}`);



    // Validate model

    if (!this.models.includes(model)) {

        throw new Error(`Model ${model} not supported`);

    }



    // Emit event for monitoring/metrics

    this.events.emit('request', { 

        type: 'completion', 

        model, 

        timestamp: new Date() 

    });



    // In a real implementation, this would call an AI model

    // Here we just echo back parts of the request with a mock response

    const response = {

        id: `mcp-resp-${Date.now()}`,

        model,

        text: `This is a response to: ${prompt.substring(0, 30)}...`,

        usage: {

        promptTokens: prompt.split(' ').length,

        completionTokens: 20,

        totalTokens: prompt.split(' ').length + 20

        }

    };



    // Simulate network delay

    await new Promise(resolve => setTimeout(resolve, 500));



    // Emit completion event

    this.events.emit('completion', {

        model,

        timestamp: new Date()

    });



    return {

        content: [

        {

            type: 'text',

            text: JSON.stringify(response)

        }

        ]

    };

}

);

Install

Run the following command:


npm install

Run


npm start

샘플

이것은 MCP 서버를 위한 Typescript 샘플입니다

도구 생성 예시는 다음과 같습니다:


this.mcpServer.tool(

'completion',

{

    model: z.string(),

    prompt: z.string(),

    options: z.object({

        temperature: z.number().optional(),

        max_tokens: z.number().optional(),

        stream: z.boolean().optional()

    }).optional()

},

async ({ model, prompt, options }) => {

    console.log(`Processing completion request for model: ${model}`);



    // Validate model

    if (!this.models.includes(model)) {

        throw new Error(`Model ${model} not supported`);

    }



    // Emit event for monitoring/metrics

    this.events.emit('request', { 

        type: 'completion', 

        model, 

        timestamp: new Date() 

    });



    // In a real implementation, this would call an AI model

    // Here we just echo back parts of the request with a mock response

    const response = {

        id: `mcp-resp-${Date.now()}`,

        model,

        text: `This is a response to: ${prompt.substring(0, 30)}...`,

        usage: {

        promptTokens: prompt.split(' ').length,

        completionTokens: 20,

        totalTokens: prompt.split(' ').length + 20

        }

    };



    // Simulate network delay

    await new Promise(resolve => setTimeout(resolve, 500));



    // Emit completion event

    this.events.emit('completion', {

        model,

        timestamp: new Date()

    });



    return {

        content: [

        {

            type: 'text',

            text: JSON.stringify(response)

        }

        ]

    };

}

);

설치

다음 명령어를 실행하세요:


npm install

실행


npm start

면책 조항:

이 문서는 AI 번역 서비스 Co-op Translator를 사용하여 번역되었습니다.

정확성을 위해 노력하고 있으나, 자동 번역에는 오류나 부정확한 부분이 있을 수 있음을 유의하시기 바랍니다.

원문은 해당 언어의 원본 문서가 권위 있는 자료로 간주되어야 합니다.

중요한 정보의 경우 전문적인 인간 번역을 권장합니다.

본 번역의 사용으로 인해 발생하는 오해나 잘못된 해석에 대해 당사는 책임을 지지 않습니다.

MCP Academy — microsoft/mcp-for-beginners