Skip to main content
Glama
Inefavel

SFMC MCP Server

by Inefavel

SFMC MCP Server

Conecte o Claude (ou qualquer client MCP) ao Salesforce Marketing Cloud. Explore Data Extensions, consulte registros e valide queries do Automation Studio antes de rodá-las.

npm version License: MIT


O problema

Quem opera SFMC conhece a rotina: você escreve uma Query Activity, salva, roda a automação — e 30 minutos depois descobre que digitou EmailAdress em vez de EmailAddress. Ou que usou um ORDER BY, que o dialeto do Automation Studio não suporta. Ou que a coluna de saída não existe na DE de destino.

O feedback loop do SFMC é medido em dezenas de minutos. Este servidor MCP reduz para segundos.

Related MCP server: Salesforce MCP Server

O que ele faz

Tool

O que resolve

validate_sql

Valida uma Query Activity antes de executar: regras do dialeto restrito do SFMC + checagem de que as DEs e colunas realmente existem

list_data_extensions

Lista DEs com metadados, filtro por nome, paginação e schema completo

query_data_extension

Consulta registros com filtro, ordenação e paginação

validate_sql em ação

Você: valide essa query pra mim

SELECT c.SubscriberKey, c.EmailAdress, c.LastPurchaseDate
FROM Customers_Master c
ORDER BY c.CreatedDate DESC
❌ INVÁLIDA — 3 erro(s) bloqueante(s).

1. ORDER BY não é suportado em Query Activities do SFMC. [linha ~3]
   → Se precisar de ranking, use ROW_NUMBER() OVER (ORDER BY ...) em subquery.

2. A coluna "EmailAdress" não existe na DE "Customers_Master".
   → Você quis dizer "EmailAddress"?

3. A coluna "LastPurchaseDate" não existe na DE "Customers_Master".
   → Campos disponíveis: SubscriberKey, EmailAddress, FirstName, Status, CreatedDate

O que ele detecta:

Regras do dialetoORDER BY, CTEs (WITH), MERGE, DML/DDL, variáveis (DECLARE @), temp tables (#temp), cursores, stored procedures, FULL OUTER JOIN, parênteses desbalanceados, SELECT * arriscado, GETDATE() em fuso do servidor.

Contra o schema real — DEs inexistentes, colunas inexistentes (com sugestão de correção via distância de edição), aliases não declarados, colunas de saída incompatíveis com a DE de destino, PK do destino ausente no SELECT (a falha silenciosa mais cara do SFMC).


Instalação

npx sfmc-mcp-server

Ou instalando localmente:

npm install -g sfmc-mcp-server

Configuração

1. Crie um Installed Package no SFMC

Setup → Apps → Installed Packages → New → Add Component → API Integration (Server-to-Server)

Permissões mínimas (somente leitura):

  • Data Extensions: Read

  • Automations: Read

Anote o Client ID, o Client Secret e o subdomínio (a parte antes de .auth.marketingcloudapis.com).

2. Configure o Claude Desktop

~/Library/Application Support/Claude/claude_desktop_config.json (macOS) %APPDATA%\Claude\claude_desktop_config.json (Windows)

{
  "mcpServers": {
    "sfmc": {
      "command": "npx",
      "args": ["-y", "sfmc-mcp-server"],
      "env": {
        "SFMC_SUBDOMAIN": "mcXXXXXXXXXXXXXXXXXXXXXX",
        "SFMC_CLIENT_ID": "seu_client_id",
        "SFMC_CLIENT_SECRET": "seu_client_secret",
        "SFMC_MODE": "read"
      }
    }
  }
}

Reinicie o Claude Desktop. Pronto.

Múltiplas Business Units

Uma entrada por BU, cada uma com seu SFMC_ACCOUNT_ID (o MID):

{
  "mcpServers": {
    "sfmc-varejo": {
      "command": "npx",
      "args": ["-y", "sfmc-mcp-server"],
      "env": { "SFMC_ACCOUNT_ID": "1234567", "...": "..." }
    },
    "sfmc-b2b": {
      "command": "npx",
      "args": ["-y", "sfmc-mcp-server"],
      "env": { "SFMC_ACCOUNT_ID": "7654321", "...": "..." }
    }
  }
}

Exemplos de uso

  • "Valide essa query contra a DE de destino Active_Buyers" → aponta erros antes de você perder 30 min

  • "Liste as DEs que têm 'master' no nome, com os campos" → schema completo sem abrir o Contact Builder

  • "Quantos registros ativos tem a Customers_Master?" → consulta direta com filtro

  • "Essa DE tem chave primária? Quais campos são NOT NULL?" → auditoria de schema em segundos


Segurança

  • Somente leitura por padrão. SFMC_MODE=read é o default. Tools de escrita (roadmap) só serão registradas com SFMC_MODE=write.

  • Credenciais apenas via variáveis de ambiente. Nunca commitadas, nunca em disco.

  • Log de auditoria. Toda tool call vai para stderr com timestamp e argumentos — redirecione para arquivo ou coletor conforme sua política.

  • Sem retenção. O servidor não persiste dados do SFMC.


Arquitetura

src/
├── index.ts               # Entry point — registra tools, transporte stdio
├── auth.ts                # OAuth client_credentials, cache de token (~20 min)
├── sfmcClient.ts          # REST client com retry exponencial (429/5xx)
└── tools/
    ├── validateSql.ts     # Regras do dialeto + validação contra schema real
    ├── listDataExtensions.ts
    └── queryDataExtension.ts

Detalhes de implementação:

  • Token com cache e margem de 60s antes da expiração (SFMC expira em ~18-20 min)

  • Retry exponencial em 429/5xx — o SFMC estrangula com facilidade sob carga

  • Auth lazy: o servidor sobe mesmo sem credenciais, valida na primeira tool call

  • Paginação forçada nas consultas (máx 50 linhas) para não estourar o contexto do modelo


Roadmap

  • get_automation_status — status e histórico de execução

  • list_journeys — journeys ativas, versões, métricas

  • get_send_stats — opens, clicks, bounces

  • upsert_rows — gravação com padrão checkpoint/resume (modo write)

  • Suporte a Shared Data Extensions do Parent BU via SOAP


Limitações conhecidas

  • A validate_sql cobre as restrições conhecidas do Automation Studio e a existência de tabelas/colunas. Não garante correção lógica nem performance.

  • DEs compartilhadas (ENT.) não são validadas contra schema — vivem no Parent BU, fora do alcance da REST da BU atual.

  • Colunas não qualificadas (sem prefixo alias.) não são validadas em queries com múltiplos JOINs — resolver isso exigiria um parser SQL completo.

  • O endpoint /data/v1/customobjects é relativamente recente. Instâncias em releases antigas podem precisar do fallback SOAP.


Contribuindo

PRs bem-vindos. As áreas de maior impacto são as tools do roadmap e novas regras de validação do dialeto SFMC — se você já perdeu tempo com uma construção que o Automation Studio rejeita, abra uma issue com o caso.

Licença

MIT

Available Tools

3 tools
list_data_extensionsA

Lista Data Extensions da Business Unit conectada, com nome, external key (customerKey), e opcionalmente os campos de cada uma. Suporta filtro por nome e paginação.

ParametersJSON Schema
NameRequiredDescriptionDefault
pageNoPágina de resultados (começa em 1).
pageSizeNoItens por página (máx 100).
nameFilterNoFiltro parcial por nome da DE (case-insensitive). Ex: 'master' encontra 'Master_Contacts'.
includeFieldsNoSe true, inclui a lista de campos (nome, tipo, tamanho, PK, nullable) de cada DE.

TDQS

A4/5.0
Behavior3/5

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

The description discloses features like pagination, name filter, and optional fields, but does not mention permission requirements, rate limits, or confirm read-only behavior. Since no annotations are provided, the description carries the full burden, and it is adequate but not exhaustive.

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, well-structured sentence that efficiently conveys the tool's purpose, optional features, and filtering support. No unnecessary words.

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

Completeness4/5

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

Given no output schema, the description adequately mentions the returned fields (name, external key, and optionally fields). The tool is simple and the description covers essential information for invocation. Could mention sorting or ordering, but not critical.

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 100%, so baseline is 3. The description adds that default returns include name and external key, but the parameter descriptions in the schema already cover the details. No significant value beyond schema.

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 lists Data Extensions from the connected Business Unit, with name and external key, and optionally fields. This distinguishes it from sibling tools query_data_extension and validate_sql, which serve different purposes.

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 use for listing Data Extensions with filtering and pagination, but does not explicitly state when not to use it versus alternatives. Since the siblings are distinct, the context is clear but lacks explicit exclusion guidance.

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

query_data_extensionA

Consulta registros de uma Data Extension pelo external key (customerKey). Suporta filtro simples (ex: "Status eq 'Active'"), ordenação e paginação. Retorna no máximo 50 linhas por chamada para não estourar o contexto.

ParametersJSON Schema
NameRequiredDescriptionDefault
pageNoPágina de resultados.
filterNoFiltro no formato do SFMC: campo operador valor. Operadores: eq, ne, gt, lt, ge, le, like. Ex: "EmailAddress like '%gmail%'" ou "SubscriberKey eq '12345'".
orderByNoCampo e direção de ordenação. Ex: 'CreatedDate desc'.
pageSizeNoLinhas por página (máx 50).
externalKeyYesExternal key (customerKey) da Data Extension.

TDQS

A3.9/5.0
Behavior3/5

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

With no annotations, the description partially compensates by mentioning pagination (max 50 rows), filter operators, and ordering. However, it lacks details on side effects (e.g., read-only guarantee), error conditions, or authorization requirements.

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 two sentences, front-loaded with the main purpose, and covers all essential features without waste. Each sentence contributes meaning.

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 no output schema, the description could better explain the response structure or field selection. It is adequate for a simple query tool but lacks details on error handling or data format.

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

Parameters4/5

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

Schema coverage is 100%, so baseline is 3. The description adds value by explaining the filter format with examples, pagination limits, and ordering syntax, going beyond the schema's 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 clearly states it queries records from a Data Extension by external key, supporting filter, ordering, and pagination. It distinguishes from sibling tools list_data_extensions and validate_sql by specifying this tool is for querying specific records.

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?

No explicit guidance on when to use this tool versus alternatives. It does not mention that list_data_extensions should be used for listing Data Extensions or validate_sql for SQL validation. Usage context is only implied.

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

validate_sqlA

Valida uma Query Activity do SFMC Automation Studio antes de executá-la. Checa construções não suportadas pelo dialeto restrito do SFMC (ORDER BY, CTE, MERGE, variáveis, temp tables, funções indisponíveis) e — se possível — confere se as Data Extensions e colunas referenciadas realmente existem. Retorna erros bloqueantes, avisos e sugestões.

ParametersJSON Schema
NameRequiredDescriptionDefault
sqlYesA query SQL do Automation Studio a ser validada.
checkSchemaNoSe true, consulta as Data Extensions referenciadas via API para validar nomes de tabelas e colunas.
targetDataExtensionNoExternal key da DE de destino da Query Activity. Se informada, valida se as colunas do SELECT cabem no schema de destino (nomes e tipos).

TDQS

A4.2/5.0
Behavior4/5

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

No annotations are provided, so the description carries full burden. It discloses what the tool checks (ORDER BY, CTE, MERGE, variables, temp tables, unsupported functions) and that it optionally validates Data Extensions and target schema. It states it returns blocking errors, warnings, and suggestions. However, it doesn't mention read-only behavior or rate limits, but for a validation tool the transparency is good.

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?

Two sentences, front-loaded with purpose. Every sentence adds value without redundancy. The structure is efficient and easy to parse.

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

Completeness4/5

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

No output schema exists, but the description explains what the tool returns (errors, warnings, suggestions). Given the tool's complexity (3 parameters, validation focus), the description covers the essential behavioral aspects. Could mention if it modifies anything, but likely not needed.

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 description coverage is 100% (all three parameters have descriptions). The tool's description adds value by setting context (e.g., highlighting that checkSchema controls DE validation), but it doesn't add meaning beyond what the schema already provides for each parameter. Baseline 3 is 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 uses specific verbs ('Valida', 'Checa', 'confere') and specifies the resource ('Query Activity do SFMC Automation Studio'). It clearly lists what is checked (unsupported constructs, existence of DEs and columns) and what is returned (errors, warnings, suggestions), distinguishing it from siblings like list_data_extensions and query_data_extension.

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 clearly states when to use this tool ('antes de executá-la' - before executing a query). It does not explicitly mention when not to use it or name alternatives, but the context is clear enough for an agent to infer appropriate usage.

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. 3 tool updatesv0.2.1
    • First observedlist_data_extensions
    • First observedquery_data_extension
    • First observedvalidate_sql

TDQS

A4.1/5.0

Scored across 3 tools

Disambiguation5/5

Each tool targets a distinct operation: listing data extensions, querying records, and validating SQL. No overlap in purpose.

Naming Consistency5/5

All tool names follow a consistent verb_noun pattern using snake_case (e.g., list_data_extensions, validate_sql).

Tool Count4/5

Three tools is slightly below the typical range but appropriate for a focused server on data extensions and SQL validation.

Completeness3/5

Covers listing, querying, and SQL validation but misses create/update/delete for data extensions, which are common workflows.

Maintenance

ActivitySlowing
ResponsivenessNo issues

Related MCP Connectors

Related MCP Servers

  • A
    license
    Not graded
    quality
    D
    maintenance
    Integrates Claude with Salesforce to enable natural language querying, modification, and management of Salesforce records and metadata. It supports comprehensive operations including object/field management, SOSL searches, and Apex code execution.
    1,360
    1
    MIT
  • A
    license
    A
    quality
    D
    maintenance
    Integrates Claude with Salesforce for natural language interactions with Salesforce data and metadata, enabling querying, modifying, and managing objects and records.
    20
    18
    MIT
  • A
    license
    A
    quality
    D
    maintenance
    Enables AI tools like Claude Desktop and Cline to interact with Salesforce, providing tools for SOQL queries, Apex execution, metadata management, and more.
    17
    33
    43
    MIT