Labsco
Log-LogN logo

Langfuse-mcp-server

โ˜… 2

from Log-LogN

MCP server for Langfuse โ€” query traces, debug errors, analyze sessions and prompts from any AI agent

๐Ÿ”ฅ๐Ÿ”ฅ๐Ÿ”ฅโœ“ VerifiedAccount requiredAdvanced setup

Langfuse MCP Server โ€” Java / Spring AI

A production-grade MCP server that connects any MCP-compatible AI agent to your Langfuse observability data.
Query traces, debug errors, inspect sessions, manage prompts, run evaluations, annotate data, and configure models โ€” all through natural language.

Transport: Streamable HTTP on port 8080, compatible with Cursor, Claude Desktop, VS Code / GitHub Copilot, and any MCP client that supports HTTP transport.


Why this server?

CapabilityThis serverOfficial Langfuse MCP
Traces & Observationsโœ…โŒ
Sessions & Usersโœ…โŒ
Exception trackingโœ…โŒ
Prompt management (read + write)โœ…โœ… read-only
Dataset & run managementโœ…โŒ
Scores & score configsโœ…โŒ
Annotation queuesโœ…โŒ
Commentsโœ…โŒ
Model definitionsโœ…โŒ
LLM connectionsโœ…โŒ
Project introspectionโœ…โŒ
Schema introspectionโœ…โŒ
Java / Spring AIโœ…โŒ (Python)

Docker

The Dockerfile is a multi-stage build: it compiles the Spring Boot jar inside Docker and runs the MCP server on port 8080. No local Maven installation is needed.

# Build image (compiles inside Docker)
docker build -t langfuse-mcp:latest .

# Run
docker run --rm -p 8080:8080 \
  -e LANGFUSE_PUBLIC_KEY=pk-lf-... \
  -e LANGFUSE_SECRET_KEY=sk-lf-... \
  -e LANGFUSE_HOST=https://cloud.langfuse.com \
  langfuse-mcp:latest

After the container starts:

EndpointURL
Health checkhttp://localhost:8080/actuator/health
Pinghttp://localhost:8080/ping
MCP endpointhttp://localhost:8080/mcp

Langfuse running in another container on the same host:

-e LANGFUSE_HOST=http://host.docker.internal:3000

Tools Reference (55 total)

Every tool returns a consistent ApiResponse<T> envelope:

{ "success": true,  "data": { ... }, "timestamp": "2025-01-15T10:30:00Z" }
{ "success": false, "errorCode": "TRACE_NOT_FOUND", "errorMessage": "...", "timestamp": "..." }

Paginated list responses wrap their items in a PagedResponse<T>:

{
  "data": [ ... ],
  "meta": { "page": 1, "limit": 20, "totalItems": 142, "totalPages": 8 }
}

Pagination is 1-based (page defaults to 1). limit defaults to 20 and is capped at 100 where noted. To page through results, increment page while keeping limit fixed.


Traces (8 tools)

ToolDescription
fetch_tracesPaginated list of traces. Filter by userId, name, sessionId, tags, fromTimestamp, toTimestamp.
fetch_traceFull detail of a single trace including nested observations, input/output, metadata, latency, and token usage. Requires traceId.
find_exceptionsTraces whose level equals ERROR. Supports time range and pagination.
find_exceptions_in_fileError-level traces whose metadata contains a given file name substring. Requires fileName.
get_exception_detailsFull detail of a single error trace. Requires traceId.
get_error_countCount of ERROR-level traces in a time range (scans up to 500 traces).
delete_tracePermanently deletes a single trace by ID. Irreversible.
delete_tracesPermanently deletes multiple traces. Pass a comma-separated list of trace IDs. Irreversible.

Sessions (3 tools)

ToolDescription
fetch_sessionsPaginated list of sessions with optional time range filter.
get_session_detailsFull session detail including all its traces. Requires sessionId.
get_user_sessionsAll sessions for a specific user with pagination. Requires userId.

Prompts (5 tools)

ToolDescription
list_promptsPaginated list of all prompts in the project.
get_promptFetch a prompt by name. Optionally pin to a version number or a label (e.g. production, staging).
create_promptCreate a new prompt or append a new version to an existing prompt. type is text (plain string) or chat (JSON array of {role, content} messages). Supports comma-separated labels and tags.
delete_promptDelete prompt versions by name. Scope to a specific label or version; omit both to delete all versions. Irreversible.
update_prompt_labelsReplace the full label set on a specific prompt version. Supply an empty string to remove all labels. The latest label is reserved by Langfuse.

Datasets (7 tools)

ToolDescription
list_datasetsPaginated list of all evaluation datasets.
get_datasetFetch a dataset by exact name.
create_datasetCreate a new dataset. Optionally supply description, metadataJson, inputSchemaJson, and expectedOutputSchemaJson (all as JSON strings).
list_dataset_itemsPaginated list of items in a dataset. Requires datasetName.
get_dataset_itemFetch a single dataset item by ID.
create_dataset_itemCreate or upsert a dataset item. Optionally link to a sourceTraceId or sourceObservationId. Supports itemId for upsert semantics.
delete_dataset_itemPermanently delete a dataset item by ID. Irreversible.

Dataset Runs (5 tools)

ToolDescription
list_dataset_runsPaginated list of experiment runs for a dataset. Requires datasetName.
get_dataset_runFull run detail including all run items. Requires datasetName and runName.
delete_dataset_runDelete a run and all its items. Irreversible. Requires datasetName and runName.
list_dataset_run_itemsPaginated list of items in a run. Requires datasetId and runName.
create_dataset_run_itemCreate a run item linking a dataset item to a trace/observation. Creates the run automatically if it does not yet exist.

Metrics (1 tool)

ToolDescription
get_cost_metricsQuery Langfuse cost, token, latency, and usage analytics via the Metrics API v1. Mirrors: GET /api/public/metrics?query=. Pass the full query as a JSON string. All aggregation is server-side.

This tool accepts a single required parameter query which must be a JSON-serialised string matching the Metrics API schema. Examples (pass these as a single JSON string):

  • Total cost last 7 days:

    {"view":"traces","metrics":[{"measure":"totalCost","aggregation":"sum"}],"fromTimestamp":"2026-03-18T00:00:00Z","toTimestamp":"2026-03-25T23:59:59Z"}

  • Daily cost trend this week:

    {"view":"traces","metrics":[{"measure":"totalCost","aggregation":"sum"},{"measure":"count","aggregation":"count"}],"timeDimension":{"granularity":"day"},"fromTimestamp":"2026-03-18T00:00:00Z","toTimestamp":"2026-03-25T23:59:59Z"}

  • Cost by model:

    {"view":"observations","dimensions":[{"field":"providedModelName"}],"metrics":[{"measure":"totalCost","aggregation":"sum"},{"measure":"totalTokens","aggregation":"sum"}],"fromTimestamp":"2026-03-18T00:00:00Z","toTimestamp":"2026-03-25T23:59:59Z"}

  • Cost for a specific user:

    {"view":"traces","metrics":[{"measure":"totalCost","aggregation":"sum"}],"filters":[{"column":"userId","operator":"=","value":"user-123","type":"string"}],"fromTimestamp":"2026-03-18T00:00:00Z","toTimestamp":"2026-03-25T23:59:59Z"}

  • Production environment only:

    filters: [{"column":"environment","operator":"=","value":"production","type":"string"}]


Scores (6 tools)

ToolDescription
get_scoresPaginated list of evaluation scores. Filter by traceId, observationId, name, dataType (NUMERIC|CATEGORICAL|BOOLEAN), and time range.
get_scoreFetch a single score by ID.
get_score_configsPaginated list of score config schemas.
get_score_configFetch a single score config by ID.
create_score_configCreate a score config. NUMERIC supports optional minValue/maxValue. CATEGORICAL accepts a categoriesJson array of {label, value} objects.
update_score_configUpdate an existing score config. Optionally set isArchived to archive it.

Annotation Queues (8 tools)

ToolDescription
list_annotation_queuesPaginated list of annotation queues.
get_annotation_queueFetch a single queue by ID.
create_annotation_queueCreate a queue for human-in-the-loop review. Optionally link a scoreConfigId.
list_annotation_queue_itemsPaginated list of items in a queue. Optionally filter by status (PENDING|COMPLETED). Requires queueId.
get_annotation_queue_itemFetch a specific queue item by queueId and itemId.
create_annotation_queue_itemAdd a trace, observation, or session to a queue for review. objectType is TRACE, OBSERVATION, or SESSION.
update_annotation_queue_itemUpdate the status of a queue item (PENDING|COMPLETED).
delete_annotation_queue_itemRemove an item from a queue. Irreversible.

Comments (3 tools)

ToolDescription
get_commentsPaginated list of comments. Optionally filter by objectType (TRACE|OBSERVATION) and objectId.
get_commentFetch a single comment by ID.
create_commentAttach a comment to a trace, observation, session, or prompt. objectType values: TRACE, OBSERVATION, SESSION, PROMPT.

Models (4 tools)

ToolDescription
list_modelsPaginated list of all model definitions (Langfuse-managed and custom).
get_modelFetch a model definition by ID.
create_modelCreate a custom model for cost tracking. Requires modelName, matchPattern (regex), and unit (TOKENS|CHARACTERS|MILLISECONDS|SECONDS|IMAGES|REQUESTS). Optionally set per-unit USD prices.
delete_modelDelete a custom model definition. Langfuse-managed models cannot be deleted. Irreversible.

LLM Connections (2 tools)

ToolDescription
list_llm_connectionsPaginated list of LLM provider connections (secret keys are masked in the response).
upsert_llm_connectionCreate or update a provider connection by provider name (e.g. openai, anthropic, azure, google). Upserts by provider โ€” if a connection already exists it is updated.

Project (1 tool)

ToolDescription
get_projects_for_api_keyReturns the project(s) visible to the configured API key. Useful for confirming credentials and project metadata.

Users (1 tool)

ToolDescription
get_user_tracesAll traces for a specific Langfuse user ID with pagination. Requires userId.

Schema (1 tool)

ToolDescription
get_data_schemaReturns the full Langfuse data model: all entity types, fields, and valid enum values. Call this first to understand the available data structures before running queries.

Architecture

MCP Client (Cursor / Claude Desktop / Copilot / other)
    โ”‚   Streamable HTTP transport (/mcp)
    โ–ผ
Tool class  (@McpTool โ€” validates required params, delegates to service)
    โ–ผ
Service interface + impl  (business logic, filtering, error mapping)
    โ–ผ
LangfuseApiClient  (HTTP gateway โ€” GET / POST / PATCH / DELETE, typed exceptions)
    โ–ผ
Langfuse Public REST API

The architecture is strictly layered:

  • client/ โ€” Langfuse integration boundary: HTTP with Basic-Auth (Apache HttpComponents 5), typed exceptions, UriComponentsBuilder for query params
  • service/ โ€” domain logic: filtering, mapping, pagination, error translation into ApiResponse
  • tools/ โ€” MCP surface: agent-friendly descriptions, parameter validation, delegation to services
  • Spring Boot โ€” runtime and transport wrapper only

API Client

LangfuseApiClient supports four HTTP methods. All methods throw LangfuseApiException or ResourceNotFoundException on error, which the service layer converts into structured ApiResponse.error(...) responses โ€” agents never see raw stack traces.

MethodUsed for
GETAll read operations
POSTCreate operations
PATCHUpdate operations
DELETEDelete operations

Package Structure

com.langfuse.mcp
โ”œโ”€โ”€ LangfuseMcpApplication.java          @SpringBootApplication @ConfigurationPropertiesScan
โ”œโ”€โ”€ config/
โ”‚   โ”œโ”€โ”€ LangfuseProperties.java          @ConfigurationProperties โ€” publicKey, secretKey, host, timeout, readOnly
โ”‚   โ”œโ”€โ”€ LangfuseClientConfig.java        RestClient bean โ€” Basic-Auth, Apache HttpComponents 5, configurable timeout
โ”‚   โ””โ”€โ”€ JacksonConfig.java               Primary ObjectMapper (JSR310, ignore unknown fields)
โ”œโ”€โ”€ client/
โ”‚   โ””โ”€โ”€ LangfuseApiClient.java           HTTP gateway (GET/POST/PATCH/DELETE); typed exceptions; UriComponentsBuilder queries
โ”œโ”€โ”€ controller/
โ”‚   โ””โ”€โ”€ PingController.java              GET /ping โ†’ {"status":"ok"}
โ”œโ”€โ”€ exception/
โ”‚   โ”œโ”€โ”€ LangfuseApiException.java        Wraps HTTP/connectivity errors โ€” statusCode + endpoint
โ”‚   โ””โ”€โ”€ ResourceNotFoundException.java   Thrown on HTTP 404
โ”œโ”€โ”€ dto/
โ”‚   โ”œโ”€โ”€ common/    ApiResponse ยท PagedResponse ยท PaginationMeta
โ”‚   โ”œโ”€โ”€ request/   Filter/get request classes (12 classes)
โ”‚   โ””โ”€โ”€ response/  Response classes (19 classes โ€” JsonNode for open-schema fields)
โ”œโ”€โ”€ service/       Interfaces (15): Trace ยท Session ยท Prompt ยท PromptWrite ยท Dataset ยท DatasetRun
โ”‚   โ”‚              ยท Score ยท AnnotationQueue ยท Comment ยท Model ยท LlmConnection ยท Project ยท User ยท Schema ยท CostMetrics
โ”‚   โ””โ”€โ”€ impl/      *ServiceImpl (15) โ€” business logic, filtering, error mapping
โ”œโ”€โ”€ tools/         @McpTool classes (15) โ€” param validation, delegation, agent-friendly descriptions
โ”‚   โ”œโ”€โ”€ TraceTools.java             (8 tools)
โ”‚   โ”œโ”€โ”€ SessionTools.java           (3 tools)
โ”‚   โ”œโ”€โ”€ PromptTools.java            (2 tools)
โ”‚   โ”œโ”€โ”€ PromptWriteTools.java       (3 tools)
โ”‚   โ”œโ”€โ”€ DatasetTools.java           (7 tools)
โ”‚   โ”œโ”€โ”€ DatasetRunTools.java        (5 tools)
โ”‚   โ”œโ”€โ”€ ScoreTools.java             (6 tools)
โ”‚   โ”œโ”€โ”€ AnnotationQueueTools.java   (8 tools)
โ”‚   โ”œโ”€โ”€ CommentTools.java           (3 tools)
โ”‚   โ”œโ”€โ”€ ModelTools.java             (4 tools)
โ”‚   โ”œโ”€โ”€ LlmConnectionTools.java     (2 tools)
โ”‚   โ”œโ”€โ”€ ProjectTools.java           (1 tool)
โ”‚   โ”œโ”€โ”€ UserTools.java              (1 tool)
โ”‚   โ”œโ”€โ”€ SchemaTools.java            (1 tool)
โ”‚   โ””โ”€โ”€ CostMetricsTools.java       (1 tool)
โ””โ”€โ”€ util/
    โ””โ”€โ”€ JsonPageMapper.java         Centralised JSON โ†’ PagedResponse mapper (no duplication)