Skip to main content
Glama
rawveg

Ollama MCP Server

ollama_chat

Chat with local LLMs using conversation history, system messages, tool calling, and adjustable generation settings.

Instructions

Chat with a model using conversation messages. Supports system messages, multi-turn conversations, tool calling, and generation options.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
modelYesName of the model to use
messagesYesArray of chat messages
toolsNoTools that the model can call (optional). Provide as JSON array of tool objects.
optionsNoGeneration options (optional). Provide as JSON object with settings like temperature, top_p, etc.
formatNojson

Implementation Reference

  • Exports toolDefinition for 'ollama_chat' containing the handler function that validates input via ChatInputSchema.parse(args) and calls chatWithModel() which invokes the Ollama API's ollama.chat() to perform conversation-based chat with a model.
    export const toolDefinition: ToolDefinition = {
      name: 'ollama_chat',
      description:
        'Chat with a model using conversation messages. Supports system messages, multi-turn conversations, tool calling, and generation options.',
      inputSchema: {
        type: 'object',
        properties: {
          model: {
            type: 'string',
            description: 'Name of the model to use',
          },
          messages: {
            type: 'array',
            description: 'Array of chat messages',
            items: {
              type: 'object',
              properties: {
                role: {
                  type: 'string',
                  enum: ['system', 'user', 'assistant'],
                },
                content: {
                  type: 'string',
                },
                images: {
                  type: 'array',
                  items: { type: 'string' },
                },
              },
              required: ['role', 'content'],
            },
          },
          tools: {
            type: 'string',
            description: 'Tools that the model can call (optional). Provide as JSON array of tool objects.',
          },
          options: {
            type: 'string',
            description: 'Generation options (optional). Provide as JSON object with settings like temperature, top_p, etc.',
          },
          format: {
            type: 'string',
            enum: ['json', 'markdown'],
            default: 'json',
          },
        },
        required: ['model', 'messages'],
      },
      handler: async (ollama: Ollama, args: Record<string, unknown>, format: ResponseFormat) => {
        const validated = ChatInputSchema.parse(args);
        return chatWithModel(
          ollama,
          validated.model,
          validated.messages,
          validated.options || {},
          format,
          validated.tools.length > 0 ? validated.tools : undefined
        );
      },
    };
  • Core chat handler function 'chatWithModel' that calls ollama.chat() with model, messages, tools, options and format, then formats and returns the response content (including tool_calls if present).
    export async function chatWithModel(
      ollama: Ollama,
      model: string,
      messages: ChatMessage[],
      options: GenerationOptions,
      format: ResponseFormat,
      tools?: Tool[]
    ): Promise<string> {
      // Determine format parameter for Ollama API
      let ollamaFormat: 'json' | undefined = undefined;
      if (format === ResponseFormat.JSON) {
        ollamaFormat = 'json';
      }
    
      const response = await ollama.chat({
        model,
        messages,
        tools,
        options,
        format: ollamaFormat,
        stream: false,
      });
    
      // Extract content with fallback
      let content = response.message.content;
      if (!content) {
        content = '';
      }
    
      const tool_calls = response.message.tool_calls;
    
      // If the response includes tool calls, include them in the output
      let hasToolCalls = false;
      if (tool_calls) {
        if (tool_calls.length > 0) {
          hasToolCalls = true;
        }
      }
    
      if (hasToolCalls) {
        const fullResponse = {
          content,
          tool_calls,
        };
        return formatResponse(JSON.stringify(fullResponse), format);
      }
    
      return formatResponse(content, format);
    }
  • ChatInputSchema Zod schema for ollama_chat tool, validating model, messages, tools (JSON parsed), options, format, and stream fields.
    /**
     * Schema for ollama_chat tool
     */
    export const ChatInputSchema = z.object({
      model: z.string().min(1),
      messages: z.array(ChatMessageSchema).min(1),
      tools: parseJsonOrDefault([]).pipe(z.array(ToolSchema)),
      options: parseJsonOrDefault({}).pipe(GenerationOptionsSchema),
      format: ResponseFormatSchema.default('json'),
      stream: z.boolean().default(false),
    });
  • src/server.ts:61-120 (registration)
    MCP server CallToolRequestSchema handler that discovers all tools via discoverTools(), finds the matching tool by name ('ollama_chat'), and invokes its handler.
    // Register tool call handler
    server.setRequestHandler(CallToolRequestSchema, async (request) => {
      try {
        const { name, arguments: args } = request.params;
    
        // Discover all tools
        const tools = await discoverTools();
    
        // Find the matching tool
        const tool = tools.find((t) => t.name === name);
    
        if (!tool) {
          throw new Error(`Unknown tool: ${name}`);
        }
    
        // Determine format from args
        const formatArg = (args as Record<string, unknown>).format;
        const format =
          formatArg === 'markdown' ? ResponseFormat.MARKDOWN : ResponseFormat.JSON;
    
        // Call the tool handler
        const result = await tool.handler(
          ollama,
          args as Record<string, unknown>,
          format
        );
    
        // Parse the result to extract structured data
        let structuredData: unknown = undefined;
        try {
          // Attempt to parse the result as JSON
          structuredData = JSON.parse(result);
        } catch {
          // If parsing fails, leave structuredData as undefined
          // This handles cases where the result is markdown or plain text
        }
    
        return {
          structuredContent: structuredData,
          content: [
            {
              type: 'text',
              text: result,
            },
          ],
        };
      } catch (error) {
        const errorMessage =
          error instanceof Error ? error.message : String(error);
        return {
          content: [
            {
              type: 'text',
              text: `Error: ${errorMessage}`,
            },
          ],
          isError: true,
        };
      }
    });
  • Auto-discovery mechanism that loads all tool definitions from the tools/ directory by importing modules that export a 'toolDefinition' matching the ToolDefinition interface.
    export async function discoverTools(): Promise<ToolDefinition[]> {
      const toolsDir = join(__dirname, 'tools');
      const files = await readdir(toolsDir);
    
      // Filter for .js files (production) or .ts files (development)
      // Exclude test files and declaration files
      const toolFiles = files.filter(
        (file) =>
          (file.endsWith('.js') || file.endsWith('.ts')) &&
          !file.includes('.test.') &&
          !file.endsWith('.d.ts')
      );
    
      const tools: ToolDefinition[] = [];
    
      for (const file of toolFiles) {
        const toolPath = join(toolsDir, file);
        const module = await import(toolPath);
    
        // Check if module exports tool metadata
        if (module.toolDefinition) {
          tools.push(module.toolDefinition);
        }
      }
    
      return tools;
    }
Behavior3/5

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

Without annotations, the description should disclose behavioral traits. It states capabilities but does not mention side effects, authentication, rate limits, or whether the tool is read-only (it is not, as it creates chat history). Basic transparency but insufficient depth.

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

Conciseness4/5

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

A single sentence listing key features. It is concise and includes the main action. However, it could be front-loaded with a clearer verb (e.g., 'Send a chat message to a model') and structured with bullet points for readability.

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 (5 params, 2 required) and no output schema, the description mentions supported features but does not detail response format or how to interpret results. It provides enough context for basic use but lacks completeness for advanced scenarios.

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?

Schema coverage is 80% (high), so the description does not need to add much. It mentions features that map to parameters (e.g., 'system messages' relates to role enum) but does not explain parameter details beyond the schema. Baseline score appropriate.

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

Purpose5/5

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

The description clearly states the tool chats with a model using conversation messages, and lists supported features (system messages, multi-turn, tool calling, options). This differentiates it from sibling tools like ollama_generate, which is likely for single-turn generation.

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

Usage Guidelines3/5

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

The description mentions features but does not provide explicit guidance on when to use this tool vs siblings like ollama_generate. It implies usage for conversational scenarios but lacks exclusion criteria or alternative recommendations.

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/rawveg/ollama-mcp'

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