Skip to main content
Glama

spark-sense-ai

License: MIT Python 3.10+

Un servidor MCP (Model Context Protocol) que ofrece a los agentes de IA — Claude Desktop, Claude Code, Devin, o cualquier cliente compatible con MCP — dos capacidades para trabajar con trabajos de Apache Spark:

  • 🔴 diagnose_spark_failure — un trabajo de Spark ha fallado; obtén una causa raíz y una solución concreta, basada en el registro de error real y en el código específico que falló.

  • 🟢 optimize_spark_performance — un trabajo de Spark se ha completado pero es lento o costoso; obtén recomendaciones de ajuste específicas y basadas en evidencia.

Creado por un ingeniero de datos con más de 12 años de experiencia práctica con Apache Spark, para llevar ese mismo instinto de depuración — «¿de qué archivo trata realmente este error y por qué?» — a un flujo de trabajo asistido por IA.


Por qué existe esto

Los fallos de Spark suelen poder diagnosticarse solo con el registro, pero leer un stack trace de 200 líneas, hacerlo coincidir con el archivo correcto en un repositorio grande con múltiples trabajos, y saber cuál de una docena de causas posibles es realmente, requiere experiencia real con Spark. Esta herramienta automatiza esa primera pasada: encuentra el código relevante (no todo el repositorio), lo entrega a un LLM junto con el registro, y obtiene un diagnóstico estructurado que puedes verificar y en el que puedes actuar.


Related MCP server: Spark MCP Optimizer

Qué lo hace diferente

Decisión de diseño

Por qué importa

Independiente del origen — EMR (ID de clúster y de paso) o una carpeta local

Funciona tanto si tu trabajo se ejecuta en AWS como on-premises/localmente

Independiente del proveedor — Bedrock, Anthropic, OpenAI, o ninguno

Sin dependencia de proveedor; provider="none" permite que el agente que llama (p. ej. Devin) razone sobre el contenido obtenido por sí mismo, sin que este servidor realice ninguna llamada a un LLM

Selección inteligente de archivos

Los proyectos grandes ejecutan muchos trabajos: esta herramienta analiza el stack trace del registro de error (Python y Scala/Java, incluidos los traces mixtos de PySpark) para incorporar solo los archivos específicos implicados en el fallo, con un máximo de 10 archivos, en lugar de volcar todo el código en el prompt

Nunca se incluyen credenciales

Cada usuario aporta sus propias credenciales de AWS y/o LLM. Aquí nada comparte facturación ni acceso entre usuarios


Ejemplo de salida

Dados este registro de error Scala de ejemplo y sus archivos de proyecto correspondientes, diagnose_spark_failure (con un proveedor configurado) devuelve:

ROOT CAUSE:
CustomerHelper.validate() calls .trim() on the "email" field without
checking for null first. Records with a missing email cause a
NullPointerException, which aborts the job after 4 failed task retries.

EVIDENCE:
- Caused by: java.lang.NullPointerException: Cannot invoke "String.trim()"
  because "email" is null
- at com.company.jobs.CustomerHelper$.validate(CustomerHelper.scala:22)
- Source shows: email.trim().nonEmpty with no null check beforehand

SUGGESTED FIX:
def validate(row: Row): Boolean = {
  val email = Option(row.getAs[String]("email"))
  email.exists(_.trim.nonEmpty)
}

CONFIDENCE: High

Observa que la herramienta incorporó automáticamente CustomerHelper.scala (el archivo al que apunta realmente el Caused by del trace), no todo el proyecto ni siquiera el archivo de entrada de nivel superior CustomerOrderJoin.scala, porque el analizador de stack traces resolvió el marco relevante más profundo.


Instalación

pip install spark-sense-ai

Instala solo los extras que vayas a usar realmente:

pip install spark-sense-ai[aws]         # for EMR source or Bedrock provider
pip install spark-sense-ai[anthropic]   # for provider="anthropic"
pip install spark-sense-ai[openai]      # for provider="openai"
pip install spark-sense-ai[all]         # everything

provider="none" con source_type="local" no necesita ningún extra — solo la dependencia base mcp.


Las cuatro formas de usarlo

#

Origen del registro/código

Proveedor de LLM

Extras necesarios

¿Se necesitan credenciales de AWS?

1

Clúster EMR + paso

Bedrock

[aws]

Sí — para la obtención y el diagnóstico

2

Clúster EMR + paso

Anthropic / OpenAI

[aws] + [anthropic|openai]

Sí — solo para la obtención

3

Carpeta local

Ninguno (el agente razona, p. ej. dentro de Devin)

ninguno

No

4

Carpeta local

Anthropic / OpenAI

[anthropic|openai]

No

Las credenciales de AWS, cuando son necesarias, se toman automáticamente de tu configuración existente (aws configure, un rol IAM adjunto o las variables de entorno AWS_* estándar) — nunca se pasan como parámetro de la herramienta.


Configuración

Claude Desktop

Edita claude_desktop_config.json:

{
  "mcpServers": {
    "sparksense": {
      "command": "sparksense-mcp",
      "env": {
        "SPARKSENSE_AWS_REGION": "ap-south-1"
      }
    }
  }
}

Claude Code

claude mcp add sparksense -- sparksense-mcp

Devin

Consulta la documentación de MCP de Devin para conocer el método de configuración actual según tu modo de agente de Devin (Cascade y Devin Local usan ubicaciones de configuración ligeramente diferentes). Configúralo para que use el comando sparksense-mcp de la misma manera que arriba.


Ejemplos de uso

"Mi trabajo de Spark ha fallado — clúster EMR j-ABC123, paso s-XYZ789. Usa sparksense para diagnosticarlo con Bedrock."

"Aquí está el registro de mi trabajo local en ./logs/error.log y el código en ./src — diagnostica el fallo."

"Sé que es jobs/customer_order_join.py el que ha fallado — usa sparksense con eso como punto de entrada."

"Usa sparksense para obtener el registro en ./logs/job.log — lo revisaré yo mismo." (provider="none" — la herramienta solo obtiene; el agente que llama hace el razonamiento)

"Mi trabajo se completó, pero tardó 40 minutos. Usa sparksense para revisar las estadísticas de ejecución en busca de oportunidades de optimización."


Referencia de la herramienta

diagnose_spark_failure

Parámetro

Obligatorio

Notas

source_type

Sí

"emr" o "local"

emr_cluster_id

Si source_type="emr"

emr_step_id

Si source_type="emr"

s3_project_location

No

URI S3 del código fuente

local_log_path

Si source_type="local"

Archivo o carpeta

local_project_path

No

Carpeta local del código fuente

job_entry_point

No

Nombre de archivo/ruta relativa específica para usar directamente, omitiendo la extracción automática — mejor cuando ya sabes qué trabajo falló

provider

No (por defecto "none")

"bedrock" / "anthropic" / "openai" / "none"

api_key

No

Para anthropic/openai; de lo contrario, lee ANTHROPIC_API_KEY / OPENAI_API_KEY

optimize_spark_performance

Mismos parámetros que arriba, más:

Parámetro

Obligatorio

Notas

current_spark_config

No

Memoria del executor, núcleos, particiones de shuffle, etc.

Lógica de selección de archivos (ambas herramientas)

1. job_entry_point given?
     → use ONLY that file. No auto-extraction.

2. Else, parse the error log for:
     → Python:      File "<path>", line <N>
     → Scala/Java:  at <package>.<Class>.<method>(<Filename>:<N>)
     (handles mixed PySpark traces — Python frames bottoming into JVM
     frames — by scanning for both patterns in the same log)
     → filters out framework/library internals (site-packages, pyspark,
       org.apache.spark, scala.*, java.*, etc.)
     → fetches up to 10 matched files

3. Else, fallback: broad scan of the project folder, capped at 10 files

Variables de entorno

Variable

Valor por defecto

Propósito

SPARKSENSE_AWS_REGION

ap-south-1

Región para las llamadas a EMR/S3/Bedrock

SPARKSENSE_BEDROCK_MODEL_ID

global.anthropic.claude-haiku-4-5-20251001-v1:0

Modelo de Bedrock a usar

ANTHROPIC_API_KEY

—

Se usa si provider="anthropic" y no se proporciona el parámetro api_key

OPENAI_API_KEY

—

Se usa si provider="openai" y no se proporciona el parámetro api_key


Pruebas

git clone https://github.com/YOUR_GITHUB_USERNAME/spark-sense-ai.git
cd spark-sense-ai
pip install -e ".[all]"

# Local source + Anthropic provider, includes Python and Scala samples
export ANTHROPIC_API_KEY="sk-ant-..."
python tests/test_local_anthropic.py

# EMR source + Bedrock provider (needs a real EMR cluster/step)
aws configure
python tests/test_emr_bedrock.py --cluster-id j-XXXXXXX --step-id s-XXXXXXX

Ambos scripts ejecutan primero una comprobación de cordura gratuita, sin llamadas a API (provider="none"), antes de realizar cualquier llamada facturable a un LLM.


Hoja de ruta

  • Disparo automático mediante Lambda/EventBridge al completarse trabajos de EMR/Glue

  • Databricks como tercer source_type

  • Integración estructurada con la API de Spark History Server

  • Detección de sesgo (skew) con estadísticas a nivel de partición

Licencia

MIT — consulta LICENSE.

Available Tools

2 tools
diagnose_spark_failureA
Read-onlyIdempotent

Diagnose why an Apache Spark job failed.

Args: source_type: Where to fetch the log/code from - "emr" or "local". emr_cluster_id: EMR cluster ID (required if source_type="emr"). emr_step_id: EMR step ID (required if source_type="emr"). s3_project_location: Optional S3 URI to the job's source code (used only if source_type="emr"). local_log_path: Path to a local log file or folder (required if source_type="local"). local_project_path: Optional local folder containing the job's source code (used only if source_type="local"). job_entry_point: Optional filename/relative path of the specific job file that ran (e.g. "jobs/customer_order_join.py"). If given, ONLY this file is used as code context - skips auto-extraction entirely. Best used when the caller already knows which job failed. If omitted, the tool automatically parses the error log's stack trace (Python and/or Scala/Java patterns - handles mixed PySpark traces) to find the relevant file(s) in the project, up to 10 files, filtering out framework/library internals. This keeps large, multi-job projects from having their entire codebase sent to the model - only the code actually implicated by the failure is included. provider: Which LLM does the reasoning - "bedrock", "anthropic", "openai", or "none" (default). "none" returns the fetched log/code as-is, for the CALLING AGENT to diagnose itself - no LLM call is made by this tool in that case. api_key: API key for "anthropic" or "openai" providers. If omitted, reads from the ANTHROPIC_API_KEY / OPENAI_API_KEY environment variable. Not used for "bedrock" (uses locally configured AWS credentials) or "none".

Returns: A structured diagnosis (root cause, evidence, fix, confidence) if a provider is set, or the raw fetched log/code for the calling agent to analyze if provider="none".

ParametersJSON Schema
NameRequiredDescriptionDefault
api_keyNo
providerNonone
emr_step_idNo
source_typeYes
emr_cluster_idNo
local_log_pathNo
job_entry_pointNo
local_project_pathNo
s3_project_locationNo

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4.5/5.0
Behavior4/5

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

The annotations (readOnlyHint=true, idempotentHint=true, destructiveHint=false) are consistent with the description, which implies fetch-and-analyze operations with no side effects. The description adds transparency about the optional LLM call and the 'none' provider returning raw data, which is valuable context beyond the annotations. No contradictions found.

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?

The description is long but well-structured, with clear sections for parameters and returns. Each piece of information serves a purpose (e.g., explaining conditional requirements, provider options, and the detection algorithm). While slightly verbose, the complexity of the tool justifies the length. It is not padded with irrelevant details.

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

Completeness5/5

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

Given the tool's complexity (multiple providers, conditional parameters, return type variations), the description is exceptionally complete. It covers return values for both provider and 'none' cases, explains the code extraction logic, and provides examples. No missing information that an agent would need to call this tool correctly.

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

Parameters5/5

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

Despite the schema having zero description coverage, the tool description explains every parameter in detail, including conditional requirements (e.g., 'required if source_type="emr"'), defaults, environment variable fallbacks, and the behavior of job_entry_point. It even includes an example and explains the auto-extraction logic. This fully compensates for the schema's lack of per-parameter descriptions.

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 opens with a specific verb and object: 'Diagnose why an Apache Spark job failed.' This clearly distinguishes the tool from the sibling 'optimize_spark_performance' by focusing on failure diagnosis rather than performance tuning. The purpose is unambiguous and immediately actionable.

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

Usage Guidelines4/5

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

The description provides thorough guidance on when to use the tool and how to configure it for different scenarios (source_type, provider, conditional parameters). It explains fallback behavior (env vars, 'none' provider) and the logic for auto-extraction. However, it does not explicitly contrast with the sibling tool, relying instead on the name difference. This is a minor gap, keeping it from a perfect score.

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

optimize_spark_performanceA
Read-onlyIdempotent

Analyze a successful Spark job's execution log/stats and suggest performance optimizations.

Args: source_type: Where to fetch the log/code from - "emr" or "local". emr_cluster_id: EMR cluster ID (required if source_type="emr"). emr_step_id: EMR step ID (required if source_type="emr"). s3_project_location: Optional S3 URI to the job's source code. local_log_path: Path to a local log file/folder (required if source_type="local"). local_project_path: Optional local folder with source code. job_entry_point: Optional filename/relative path of the specific job file to focus on. If given, ONLY this file is used - skips auto-extraction. If omitted, the tool parses the execution log for stack-trace-like file references (Python and/or Scala/Java) to narrow down which of the project's files are relevant, up to 10 files. Useful for large, multi-job repositories. current_spark_config: Optional text describing the current Spark configuration (executor memory, cores, shuffle partitions, etc.), to ground recommendations in what's configurable. provider: "bedrock", "anthropic", "openai", or "none" (default - returns fetched content for the calling agent to analyze). api_key: API key for "anthropic"/"openai". Reads from env var if omitted. Unused for "bedrock" or "none".

Returns: A structured analysis (observations, recommendations, estimated impact) if a provider is set, or the raw fetched content for the calling agent to analyze if provider="none".

ParametersJSON Schema
NameRequiredDescriptionDefault
api_keyNo
providerNonone
emr_step_idNo
source_typeYes
emr_cluster_idNo
local_log_pathNo
job_entry_pointNo
local_project_pathNo
s3_project_locationNo
current_spark_configNo

Output Schema

ParametersJSON Schema
NameRequiredDescription
resultYes

TDQS

A4.6/5.0
Behavior4/5

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

Annotations already declare readOnly, idempotent, openWorld, and non-destructive. The description adds clarity by explaining that with provider='none' it returns raw fetched content, and otherwise returns a structured analysis. There is no contradiction with annotations, and the description provides useful context on what the tool does without describing side effects.

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 well-organized with a main purpose statement, an Args section listing each parameter with explanations, and a Returns section. It is thorough but not redundant, providing all necessary information without unnecessary verbosity.

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

Completeness5/5

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

The description explains the full behavior of the tool: what it analyzes, how it uses the parameters, and what it returns under different provider settings. Although an explicit output schema is not shown, the description clearly describes the two possible return types (structured analysis or raw content), making it complete for the agent to use correctly.

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

Parameters5/5

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

The schema has 0% description coverage for its 10 parameters, but the tool description compensates fully by explaining each parameter: source_type, emr_cluster_id, emr_step_id, s3_project_location, local_log_path, local_project_path, job_entry_point, current_spark_config, provider, and api_key. It clarifies requirements (e.g., 'required if source_type=...') and optionality, making the semantics complete.

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's purpose: analyze successful Spark job logs/stats and suggest performance optimizations. It names the specific action (analyze, suggest) and resource (execution log/stats), and differentiates from the sibling tool by emphasizing 'successful' jobs, implying a contrast with failure diagnosis.

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

Usage Guidelines4/5

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

The description implies when to use the tool (for successful jobs to get optimization suggestions) by contrasting with 'successful' and the sibling 'diagnose_spark_failure'. It also explains provider options (including 'none' for raw content) and argument dependencies. However, it does not explicitly state 'use this instead of diagnose_spark_failure when the job succeeded,' leaving the distinction implicit.

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

Tool Schema Changelog

Recent tool additions, removals, and schema changes observed during successful MCP inspections.

  1. 2 tool updatesv0.1.3
    • First observeddiagnose_spark_failure
    • First observedoptimize_spark_performance

TDQS

A4.6/5.0

Scored across 2 tools

Disambiguation5/5

The two tools have clearly distinct purposes: one diagnoses failures and the other optimizes performance. Despite sharing similar arguments, their actions and return types are unambiguously different.

Naming Consistency5/5

Both tool names follow the consistent verb_noun pattern (diagnose_spark_failure, optimize_spark_performance), which is clear and predictable.

Tool Count4/5

With only two tools, the server is slightly below the typical well-scoped range, but it is focused on a narrow domain (Spark job analysis) where these two core operations are appropriate.

Completeness4/5

The server covers the primary needs of diagnosing failures and optimizing performance. However, there may be gaps such as retrieving job metrics or listing available jobs, though these are not strictly required for the stated purpose.

Maintenance

ActivitySlowing
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers