Skip to main content

LLM Module - MCP Tool Specification

This document defines the Model Context Protocol (MCP) tools for the llm module, which provides comprehensive Large Language Model integration including local model management (Ollama), multi-provider support, embeddings, RAG, guardrails, and cost tracking.

General Considerations for LLM Tools​

  • Dependencies: Requires logging_monitoring module. External dependencies vary by provider (openai, anthropic SDKs). Ollama requires local installation.
  • Initialization: Provider-specific clients initialized on first use. Ollama server may auto-start.
  • Error Handling: Errors logged via logging_monitoring. Provider-specific errors wrapped in standardized format.
  • Security: API keys read from environment or config. Prompts/responses may be logged (configurable). PII detection available via guardrails.

Tool: llm_complete​

1. Tool Purpose and Description​

Generates text completions using configured LLM providers (OpenAI, Anthropic, Ollama, etc.). Supports chat-style multi-turn conversations with system prompts, streaming, and tool calling.

2. Invocation Name​

llm_complete

3. Input Schema (Parameters)​

Parameter NameTypeRequiredDescriptionExample Value
messagesarray[object]YesConversation messagesSee below
messages[].roleenum["system", "user", "assistant", "tool"]YesMessage role"user"
messages[].contentstringYesMessage content"Explain quantum computing"
providerenum["openai", "anthropic", "ollama", "google", "mistral"]NoLLM provider. Default: "openai""anthropic"
modelstringNoSpecific model. Default: provider default"claude-3-5-sonnet-20241022"
temperaturefloatNoSampling temperature (0-2). Default: 0.70.5
max_tokensintegerNoMaximum response tokens. Default: provider default2048
streambooleanNoEnable streaming response. Default: falsefalse

4. Output Schema (Return Value)​

Field NameTypeDescriptionExample Value
successbooleanWhether completion succeededtrue
contentstringGenerated response text"Quantum computing uses..."
modelstringModel used for generation"gpt-4o"
providerstringProvider used"openai"
finish_reasonstringWhy generation stopped"stop"
usageobjectToken usage statisticsSee below
usage.prompt_tokensintegerInput tokens125
usage.completion_tokensintegerOutput tokens456
usage.total_tokensintegerTotal tokens581
tool_callsarray[object]Tool calls requested (if any)null

5. Error Handling​

  • ProviderError: Provider API unavailable or returned error
  • AuthenticationError: Invalid or missing API key
  • RateLimitError: Provider rate limit exceeded
  • ModelNotFoundError: Specified model not available
  • Return Format: {"success": false, "error": "Completion failed: <details>", "error_type": "rate_limit"}

6. Idempotency​

  • Idempotent: No
  • Explanation: LLM outputs are stochastic. Temperature=0 increases consistency but does not guarantee identical outputs.

7. Usage Examples (for MCP context)​

{
"tool_name": "llm_complete",
"arguments": {
"messages": [
{"role": "system", "content": "You are a helpful coding assistant."},
{"role": "user", "content": "Write a Python function to calculate Fibonacci numbers"}
],
"provider": "anthropic",
"model": "claude-3-5-sonnet-20241022",
"temperature": 0.3,
"max_tokens": 1024
}
}

8. Security Considerations​

  • Input Validation: Messages validated for structure. Content checked via guardrails if enabled.
  • Permissions: Requires valid API key for chosen provider.
  • Data Handling: Prompts and responses sent to external providers. Do not include secrets in prompts.
  • Rate Limiting: Respect provider rate limits; implement exponential backoff.

Tool: llm_ollama_run​

1. Tool Purpose and Description​

Runs inference on locally-hosted Ollama models. Provides privacy-preserving local execution with no data sent to external services.

2. Invocation Name​

llm_ollama_run

3. Input Schema (Parameters)​

Parameter NameTypeRequiredDescriptionExample Value
model_namestringYesOllama model to run"llama3:8b"
promptstringYesInput prompt"Explain neural networks"
system_promptstringNoSystem instruction"You are a teacher"
optionsobjectNoModel optionsSee below
options.temperaturefloatNoSampling temperature. Default: 0.80.5
options.top_pfloatNoTop-p sampling. Default: 0.90.95
options.num_predictintegerNoMax tokens to generate. Default: 20481024
save_outputbooleanNoSave output to file. Default: falsetrue
output_dirstringNoDirectory for saved outputs"./output/ollama/"

4. Output Schema (Return Value)​

Field NameTypeDescriptionExample Value
successbooleanWhether execution succeededtrue
model_namestringModel used"llama3:8b"
promptstringInput prompt"Explain neural networks"
responsestringGenerated response"Neural networks are..."
execution_timefloatGeneration time in seconds3.45
tokens_usedintegerApproximate tokens generated256
error_messagestringError details if failednull
metadataobjectAdditional execution metadata{"api_method": "http"}

5. Error Handling​

  • ModelNotAvailableError: Model not downloaded to Ollama
  • ServerNotRunningError: Ollama server not running
  • TimeoutError: Generation exceeded timeout
  • Return Format: {"success": false, "error": "Ollama execution failed: <details>"}

6. Idempotency​

  • Idempotent: No
  • Explanation: LLM outputs are stochastic even with same inputs.

7. Usage Examples (for MCP context)​

{
"tool_name": "llm_ollama_run",
"arguments": {
"model_name": "codellama:13b",
"prompt": "Write a Python function to parse JSON safely",
"system_prompt": "You are an expert Python developer. Write clean, well-documented code.",
"options": {
"temperature": 0.3,
"num_predict": 512
}
}
}

8. Security Considerations​

  • Input Validation: Model name validated against available models.
  • Permissions: Local execution only; no external API calls.
  • Data Handling: All data remains local. Output files created in specified directory.
  • File Paths: Output directory validated and sandboxed.

Tool: llm_ollama_list_models​

1. Tool Purpose and Description​

Lists all Ollama models available locally, including model metadata such as size, parameter count, and family.

2. Invocation Name​

llm_ollama_list_models

3. Input Schema (Parameters)​

Parameter NameTypeRequiredDescriptionExample Value
force_refreshbooleanNoForce refresh of cached model list. Default: falsetrue

4. Output Schema (Return Value)​

Field NameTypeDescriptionExample Value
successbooleanWhether listing succeededtrue
modelsarray[object]Available modelsSee below
models[].namestringModel name"llama3:8b"
models[].idstringModel digest ID"abc123def456"
models[].sizeintegerSize in bytes4500000000
models[].size_gbfloatSize in GB4.5
models[].modifiedstringLast modified date"2026-01-15"
models[].parametersstringParameter size"8B"
models[].familystringModel family"llama"
total_countintegerTotal models available5
total_size_gbfloatTotal storage used25.3

5. Error Handling​

  • ServerNotRunningError: Ollama server not running
  • Return Format: {"success": false, "error": "Failed to list models: <details>"}

6. Idempotency​

  • Idempotent: Yes
  • Explanation: Read-only query of available models.

7. Usage Examples (for MCP context)​

{
"tool_name": "llm_ollama_list_models",
"arguments": {
"force_refresh": true
}
}

8. Security Considerations​

  • Input Validation: No user-supplied paths or code.
  • Permissions: Read-only access to Ollama API.
  • Data Handling: Model metadata only; no sensitive data.

Tool: llm_ollama_pull_model​

1. Tool Purpose and Description​

Downloads (pulls) a model from the Ollama library to local storage. Large models may take significant time to download.

2. Invocation Name​

llm_ollama_pull_model

3. Input Schema (Parameters)​

Parameter NameTypeRequiredDescriptionExample Value
model_namestringYesModel to download"llama3:70b"

4. Output Schema (Return Value)​

Field NameTypeDescriptionExample Value
successbooleanWhether download completedtrue
model_namestringDownloaded model"llama3:70b"
messagestringStatus message"Model downloaded successfully"

5. Error Handling​

  • ModelNotFoundError: Model does not exist in Ollama library
  • DiskSpaceError: Insufficient disk space
  • NetworkError: Download failed due to network issues
  • Return Format: {"success": false, "error": "Model pull failed: <details>"}

6. Idempotency​

  • Idempotent: Yes
  • Explanation: Re-downloading an existing model is a no-op (model already present).

7. Usage Examples (for MCP context)​

{
"tool_name": "llm_ollama_pull_model",
"arguments": {
"model_name": "codellama:34b"
}
}

8. Security Considerations​

  • Input Validation: Model name validated against Ollama library format.
  • Permissions: Requires write access to Ollama model directory.
  • Data Handling: Model downloaded from Ollama registry (ollama.com).
  • Network: Requires internet access during download.

Tool: llm_embed​

1. Tool Purpose and Description​

Generates text embeddings (vector representations) for semantic search, similarity matching, and RAG applications. Supports multiple embedding providers and models.

2. Invocation Name​

llm_embed

3. Input Schema (Parameters)​

Parameter NameTypeRequiredDescriptionExample Value
textstringYes (if texts not provided)Single text to embed"Machine learning is..."
textsarray[string]Yes (if text not provided)Multiple texts to embed["text1", "text2"]
modelenum["text-embedding-ada-002", "text-embedding-3-small", "text-embedding-3-large"]NoEmbedding model. Default: "text-embedding-3-small""text-embedding-3-large"
use_cachebooleanNoUse embedding cache. Default: truetrue

4. Output Schema (Return Value)​

Field NameTypeDescriptionExample Value
successbooleanWhether embedding succeededtrue
embeddingsarray[object]Generated embeddingsSee below
embeddings[].vectorarray[float]Embedding vector[0.023, -0.045, ...]
embeddings[].textstringSource text"Machine learning is..."
embeddings[].dimensionsintegerVector dimensions1536
modelstringModel used"text-embedding-3-small"
cache_hitsintegerEmbeddings retrieved from cache1
api_callsintegerNew API calls made1

5. Error Handling​

  • ProviderError: Embedding API unavailable
  • InputTooLongError: Text exceeds model's token limit
  • Return Format: {"success": false, "error": "Embedding failed: <details>"}

6. Idempotency​

  • Idempotent: Yes
  • Explanation: Same text produces identical embedding vectors.

7. Usage Examples (for MCP context)​

{
"tool_name": "llm_embed",
"arguments": {
"texts": [
"Codomyrmex is a modular development platform",
"Machine learning enables intelligent automation"
],
"model": "text-embedding-3-small",
"use_cache": true
}
}

8. Security Considerations​

  • Input Validation: Text length validated against model limits.
  • Permissions: Requires API key for embedding provider.
  • Data Handling: Text sent to external API for embedding.
  • Caching: Cached embeddings stored locally; clear cache if processing sensitive data.

1. Tool Purpose and Description​

Performs semantic similarity search against an embedding index. Finds the most similar documents/chunks to a query using cosine similarity.

2. Invocation Name​

llm_similarity_search

3. Input Schema (Parameters)​

Parameter NameTypeRequiredDescriptionExample Value
querystringYesSearch query text"How do I execute code safely?"
index_namestringNoNamed index to search. Default: "default""documentation"
kintegerNoNumber of results. Default: 510
thresholdfloatNoMinimum similarity score (0-1). Default: none0.7

4. Output Schema (Return Value)​

Field NameTypeDescriptionExample Value
successbooleanWhether search succeededtrue
resultsarray[object]Similar items foundSee below
results[].textstringMatched text content"The coding module provides..."
results[].scorefloatSimilarity score (0-1)0.89
results[].rankintegerResult ranking1
results[].metadataobjectAssociated metadata{"source": "README.md"}
total_searchedintegerItems in index1250
query_embedding_time_msfloatTime to embed query45.2
search_time_msfloatTime to search index12.3

5. Error Handling​

  • IndexNotFoundError: Specified index does not exist
  • EmbeddingError: Failed to embed query
  • Return Format: {"success": false, "error": "Search failed: <details>"}

6. Idempotency​

  • Idempotent: Yes
  • Explanation: Same query produces same results (given unchanged index).

7. Usage Examples (for MCP context)​

{
"tool_name": "llm_similarity_search",
"arguments": {
"query": "How do I run code in a Docker container?",
"index_name": "codomyrmex-docs",
"k": 5,
"threshold": 0.6
}
}

8. Security Considerations​

  • Input Validation: Query text validated and embedded securely.
  • Permissions: Read access to embedding index.
  • Data Handling: Query sent to embedding provider; results from local index.

Tool: llm_rag_query​

1. Tool Purpose and Description​

Performs Retrieval-Augmented Generation (RAG): retrieves relevant context from an index and generates a response grounded in that context. Reduces hallucination by providing factual grounding.

2. Invocation Name​

llm_rag_query

3. Input Schema (Parameters)​

Parameter NameTypeRequiredDescriptionExample Value
querystringYesUser question"How do I configure Ollama?"
index_namestringNoDocument index to search. Default: "default""docs"
kintegerNoNumber of context chunks. Default: 53
providerstringNoLLM provider for generation. Default: "openai""anthropic"
modelstringNoModel for generation"gpt-4o"
include_sourcesbooleanNoInclude source references. Default: truetrue

4. Output Schema (Return Value)​

Field NameTypeDescriptionExample Value
successbooleanWhether RAG completedtrue
answerstringGenerated answer"To configure Ollama, you..."
sourcesarray[object]Context chunks usedSee below
sources[].textstringSource text"Ollama configuration..."
sources[].scorefloatRelevance score0.92
sources[].document_idstringSource document"ollama-readme"
context_usedstringFull context provided to LLM"Source 1:..."
retrieval_time_msfloatTime for retrieval89.4
generation_time_msfloatTime for generation1234.5

5. Error Handling​

  • IndexNotFoundError: Document index not available
  • GenerationError: LLM generation failed
  • Return Format: {"success": false, "error": "RAG query failed: <details>"}

6. Idempotency​

  • Idempotent: No
  • Explanation: LLM generation is stochastic. Retrieval is deterministic.

7. Usage Examples (for MCP context)​

{
"tool_name": "llm_rag_query",
"arguments": {
"query": "What security measures does the coding module use for code execution?",
"index_name": "codomyrmex-docs",
"k": 4,
"provider": "anthropic",
"model": "claude-3-5-sonnet-20241022",
"include_sources": true
}
}

8. Security Considerations​

  • Input Validation: Query sanitized before retrieval and generation.
  • Permissions: Requires access to index and LLM provider.
  • Data Handling: Retrieved context sent to LLM provider.
  • Grounding: Responses grounded in retrieved context to reduce hallucination.

Tool: llm_check_guardrails​

1. Tool Purpose and Description​

Validates input/output against safety guardrails including prompt injection detection, PII detection, and content filtering. Essential for production LLM applications.

2. Invocation Name​

llm_check_guardrails

3. Input Schema (Parameters)​

Parameter NameTypeRequiredDescriptionExample Value
textstringYesText to check"Ignore previous instructions..."
check_typeenum["input", "output", "both"]NoType of check. Default: "input""input"
checksarray[enum["injection", "pii", "content", "length"]]NoSpecific checks. Default: all["injection", "pii"]
sanitizebooleanNoSanitize PII if detected. Default: falsetrue

4. Output Schema (Return Value)​

Field NameTypeDescriptionExample Value
successbooleanWhether checks completedtrue
passedbooleanWhether all checks passedfalse
is_safebooleanWhether content is safe to proceedfalse
threat_levelenum["none", "low", "medium", "high", "critical"]Detected threat level"high"
actionenum["allow", "warn", "block", "sanitize"]Recommended action"block"
threats_detectedarray[string]List of detected threats["Prompt injection pattern detected"]
pii_foundarray[string]Types of PII detected["email", "phone"]
sanitized_contentstringPII-sanitized version (if requested)"Contact [EMAIL] at [PHONE]"

5. Error Handling​

  • GuardrailError: Check could not be performed
  • Return Format: {"success": false, "error": "Guardrail check failed: <details>"}

6. Idempotency​

  • Idempotent: Yes
  • Explanation: Same input produces same guardrail results.

7. Usage Examples (for MCP context)​

{
"tool_name": "llm_check_guardrails",
"arguments": {
"text": "Please help me understand machine learning. My email is user@example.com",
"check_type": "input",
"checks": ["injection", "pii"],
"sanitize": true
}
}

8. Security Considerations​

  • Input Validation: Text analyzed for security threats.
  • Permissions: No external calls; runs locally.
  • Data Handling: PII detection is local; text not transmitted.
  • Blocking: High-threat content should be blocked from LLM processing.

Tool: llm_estimate_cost​

1. Tool Purpose and Description​

Estimates the cost of an LLM request before making it. Helps with budget management and cost-aware model selection.

2. Invocation Name​

llm_estimate_cost

3. Input Schema (Parameters)​

Parameter NameTypeRequiredDescriptionExample Value
model_idstringYesModel to estimate cost for"gpt-4o"
input_textstringYesInput prompt text"Explain this concept..."
estimated_output_tokensintegerNoExpected output tokens. Default: 5001000

4. Output Schema (Return Value)​

Field NameTypeDescriptionExample Value
successbooleanWhether estimation succeededtrue
model_idstringModel priced"gpt-4o"
input_tokensintegerEstimated input tokens125
output_tokensintegerEstimated output tokens500
estimated_costfloatTotal estimated cost in USD0.0053
input_costfloatInput token cost0.0003
output_costfloatOutput token cost0.005
pricingobjectModel pricing infoSee below
pricing.input_per_1kfloatCost per 1K input tokens0.0025
pricing.output_per_1kfloatCost per 1K output tokens0.01

5. Error Handling​

  • ModelNotFoundError: Pricing not available for model
  • Return Format: {"success": false, "error": "Cost estimation failed: <details>"}

6. Idempotency​

  • Idempotent: Yes
  • Explanation: Same inputs produce same cost estimate.

7. Usage Examples (for MCP context)​

{
"tool_name": "llm_estimate_cost",
"arguments": {
"model_id": "claude-3-5-sonnet",
"input_text": "Analyze this codebase and provide detailed recommendations for improving code quality, performance, and maintainability...",
"estimated_output_tokens": 2000
}
}

8. Security Considerations​

  • Input Validation: Model ID validated against known pricing data.
  • Permissions: No external calls; uses local pricing data.
  • Data Handling: No sensitive data processed.

Tool: llm_track_usage​

1. Tool Purpose and Description​

Records LLM usage for cost tracking and analytics. Provides usage summaries, budget monitoring, and historical analysis.

2. Invocation Name​

llm_track_usage

3. Input Schema (Parameters)​

Parameter NameTypeRequiredDescriptionExample Value
actionenum["record", "summary", "export"]YesTracking action"record"
model_idstringConditionalModel used (required for "record")"gpt-4o"
input_tokensintegerConditionalInput tokens (required for "record")500
output_tokensintegerConditionalOutput tokens (required for "record")200
latency_msfloatNoRequest latency1234.5
period_daysintegerNoSummary period (for "summary"). Default: 307

4. Output Schema (Return Value)​

For action="record":

Field NameTypeDescriptionExample Value
successbooleanWhether recording succeededtrue
record_idstringRecorded entry ID"rec-abc123"
costfloatCalculated cost0.0045

For action="summary":

Field NameTypeDescriptionExample Value
successbooleanWhether summary succeededtrue
period_startstringSummary start date"2026-01-27"
period_endstringSummary end date"2026-02-03"
total_requestsintegerTotal API calls156
total_tokensintegerTotal tokens used125000
total_costfloatTotal cost12.45
by_modelobjectBreakdown by modelSee below

5. Error Handling​

  • TrackingError: Unable to record or retrieve usage
  • Return Format: {"success": false, "error": "Usage tracking failed: <details>"}

6. Idempotency​

  • Idempotent: No for "record" (creates new entry), Yes for "summary"/"export"
  • Explanation: Recording creates new entries; queries are read-only.

7. Usage Examples (for MCP context)​

{
"tool_name": "llm_track_usage",
"arguments": {
"action": "summary",
"period_days": 7
}
}

8. Security Considerations​

  • Input Validation: Token counts validated as positive integers.
  • Permissions: Usage data stored locally.
  • Data Handling: Usage statistics may reveal API usage patterns.

Tool: llm_list_providers​

1. Tool Purpose and Description​

Lists all available LLM providers with their configuration status, available models, and capabilities.

2. Invocation Name​

llm_list_providers

3. Input Schema (Parameters)​

Parameter NameTypeRequiredDescriptionExample Value
include_modelsbooleanNoInclude available models per provider. Default: truetrue
check_availabilitybooleanNoTest provider connectivity. Default: falsetrue

4. Output Schema (Return Value)​

Field NameTypeDescriptionExample Value
successbooleanWhether listing succeededtrue
providersarray[object]Available providersSee below
providers[].namestringProvider name"openai"
providers[].configuredbooleanAPI key configuredtrue
providers[].availablebooleanProvider responding (if checked)true
providers[].default_modelstringDefault model"gpt-4o"
providers[].modelsarray[string]Available models["gpt-4o", "gpt-4o-mini"]
default_providerstringSystem default provider"openai"

5. Error Handling​

  • Return Format: {"success": false, "error": "Provider listing failed: <details>"}

6. Idempotency​

  • Idempotent: Yes
  • Explanation: Read-only query of provider configuration.

7. Usage Examples (for MCP context)​

{
"tool_name": "llm_list_providers",
"arguments": {
"include_models": true,
"check_availability": true
}
}

8. Security Considerations​

  • Input Validation: No user-supplied sensitive data.
  • Permissions: May make test API calls if check_availability is true.
  • Data Handling: API keys not exposed; only configuration status shown.