Skip to main content
Glama
NightTrek

Ollama MCP Server

by NightTrek

chat_completion

Generate AI responses using local Ollama models through an OpenAI-compatible API for chat-based applications.

Instructions

OpenAI-compatible chat completion API

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
modelYesName of the Ollama model to use
messagesYesArray of messages in the conversation
temperatureNoSampling temperature (0-2)
timeoutNoTimeout in milliseconds (default: 60000)

Implementation Reference

  • The handler function that implements the core logic of the chat_completion tool. Converts messages to a prompt, calls Ollama generate API, and returns formatted OpenAI-compatible response.
    private async handleChatCompletion(args: any) {
      try {
        // Convert chat messages to a single prompt
        const prompt = args.messages
          .map((msg: any) => {
            switch (msg.role) {
              case 'system':
                return `System: ${msg.content}\n`;
              case 'user':
                return `User: ${msg.content}\n`;
              case 'assistant':
                return `Assistant: ${msg.content}\n`;
              default:
                return '';
            }
          })
          .join('');
    
        // Make request to Ollama API with configurable timeout and raw mode
        const response = await axios.post<OllamaGenerateResponse>(
          `${OLLAMA_HOST}/api/generate`,
          {
            model: args.model,
            prompt,
            stream: false,
            temperature: args.temperature,
            raw: true, // Add raw mode for more direct responses
          },
          {
            timeout: args.timeout || DEFAULT_TIMEOUT,
          }
        );
    
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify({
                id: 'chatcmpl-' + Date.now(),
                object: 'chat.completion',
                created: Math.floor(Date.now() / 1000),
                model: args.model,
                choices: [
                  {
                    index: 0,
                    message: {
                      role: 'assistant',
                      content: response.data.response,
                    },
                    finish_reason: 'stop',
                  },
                ],
              }, null, 2),
            },
          ],
        };
      } catch (error) {
        if (axios.isAxiosError(error)) {
          throw new McpError(
            ErrorCode.InternalError,
            `Ollama API error: ${error.response?.data?.error || error.message}`
          );
        }
        throw new McpError(ErrorCode.InternalError, `Unexpected error: ${formatError(error)}`);
      }
    }
  • Input schema definition for the chat_completion tool, specifying parameters like model, messages, temperature, and timeout.
    inputSchema: {
      type: 'object',
      properties: {
        model: {
          type: 'string',
          description: 'Name of the Ollama model to use',
        },
        messages: {
          type: 'array',
          items: {
            type: 'object',
            properties: {
              role: {
                type: 'string',
                enum: ['system', 'user', 'assistant'],
              },
              content: {
                type: 'string',
              },
            },
            required: ['role', 'content'],
          },
          description: 'Array of messages in the conversation',
        },
        temperature: {
          type: 'number',
          description: 'Sampling temperature (0-2)',
          minimum: 0,
          maximum: 2,
        },
        timeout: {
          type: 'number',
          description: 'Timeout in milliseconds (default: 60000)',
          minimum: 1000,
        },
      },
      required: ['model', 'messages'],
      additionalProperties: false,
    },
  • src/index.ts:207-249 (registration)
    Registration of the chat_completion tool in the ListTools response, including name, description, and input schema.
    {
      name: 'chat_completion',
      description: 'OpenAI-compatible chat completion API',
      inputSchema: {
        type: 'object',
        properties: {
          model: {
            type: 'string',
            description: 'Name of the Ollama model to use',
          },
          messages: {
            type: 'array',
            items: {
              type: 'object',
              properties: {
                role: {
                  type: 'string',
                  enum: ['system', 'user', 'assistant'],
                },
                content: {
                  type: 'string',
                },
              },
              required: ['role', 'content'],
            },
            description: 'Array of messages in the conversation',
          },
          temperature: {
            type: 'number',
            description: 'Sampling temperature (0-2)',
            minimum: 0,
            maximum: 2,
          },
          timeout: {
            type: 'number',
            description: 'Timeout in milliseconds (default: 60000)',
            minimum: 1000,
          },
        },
        required: ['model', 'messages'],
        additionalProperties: false,
      },
    },
  • src/index.ts:274-275 (registration)
    Dispatch in CallToolRequestHandler switch statement that routes chat_completion calls to the handler function.
    case 'chat_completion':
      return await this.handleChatCompletion(request.params.arguments);
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries the full burden of behavioral disclosure. It mentions 'OpenAI-compatible' but doesn't specify key traits like whether it's read-only or destructive, authentication needs, rate limits, or response formats. This leaves significant gaps for a tool that likely involves API calls and text generation.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness5/5

Is the description appropriately sized, front-loaded, and free of redundancy?

The description is a single, efficient sentence that directly states the tool's function without unnecessary details. It's appropriately sized and front-loaded, with zero waste, making it easy for an agent to grasp the core purpose quickly.

Shorter descriptions cost fewer tokens and are easier for agents to parse. Every sentence should earn its place.

Completeness3/5

Given the tool's complexity, does the description cover enough for an agent to succeed on first attempt?

Given the tool's complexity (involving model interactions and multiple parameters) and no output schema, the description is incomplete. It lacks details on return values, error handling, or behavioral traits. However, the high schema coverage provides some compensation, resulting in an adequate but minimal score.

Complex tools with many parameters or behaviors need more documentation. Simple tools need less. This dimension scales expectations accordingly.

Parameters3/5

Does the description clarify parameter syntax, constraints, interactions, or defaults beyond what the schema provides?

The input schema has 100% description coverage, so the schema fully documents all parameters. The description adds no additional meaning beyond the schema, such as explaining the 'OpenAI-compatible' context for parameters. This meets the baseline score of 3, as the schema handles the heavy lifting.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/5

Does the description clearly state what the tool does and how it differs from similar tools?

The description clearly states the tool's purpose as an 'OpenAI-compatible chat completion API,' which indicates it generates text responses in a conversational format. It specifies the verb 'completion' and resource 'chat,' though it doesn't differentiate from siblings like 'run' or 'serve' that might also involve model interactions, keeping it from a perfect score.

Agents choose between tools based on descriptions. A clear purpose with a specific verb and resource helps agents select the right tool.

Usage Guidelines2/5

Does the description explain when to use this tool, when not to, or what alternatives exist?

No guidance is provided on when to use this tool versus alternatives. The description lacks context about scenarios like generating text, handling conversations, or comparisons with other tools such as 'run' or 'serve,' leaving the agent without usage direction.

Agents often have multiple tools that could apply. Explicit usage guidance like "use X instead of Y when Z" prevents misuse.

Install Server

Other Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/NightTrek/Ollama-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server