Skip to main content
Glama
MCP Visual
by Mauricioo67

MCP Visual

Servidor Model Context Protocol que expone soluciones de .NET / Visual Studio (.sln, .slnx, .csproj) a cualquier agente de trabajo (agent harness): Claude Code, Claude Desktop, Cursor, Cline, VS Code, o cualquier cliente MCP propio.

El agente no necesita entender el formato de disco de Visual Studio: pide la solución, los proyectos, los ficheros o el grafo de dependencias y recibe JSON estructurado.

Características

  • 14 tools (una clase por tool, un schema Zod por tool) y 4 resources + 1 template para lectura cacheable, y 3 prompts versionados en el servidor.

  • Completions, resources/subscribe con notificaciones por cambios en disco y structuredContent en las respuestas de las tools.

  • Herencia de MSBuild: Directory.Build.props, Directory.Packages.props e Import; búsqueda de símbolos C#, ciclos en el grafo y assets declarados en ItemGroup.

  • Transportes STDIO (por defecto) y HTTP Streamable con sesiones (Mcp-Session-Id, GET/SSE, DELETE, TTL de sesión, respuestas JSON para clientes sin SSE).

  • Soporte de .sln clásico y .slnx (formato XML de .NET 9).

  • Arquitectura en capas con SOLID y dependencias hacia dentro; un único composition root.

  • Rutas siempre confinadas al PROJECT_ROOT (protección contra path traversal).

  • Paginación limit/offset con nextOffset en todas las listas y proyección view=summary.

  • Errores JSON-RPC tipados (-32602, -32601, -32603, -32000) con data, nunca stack traces.

  • Observabilidad: logs estructurados a stderr, métricas por tool y GET /stats.

  • Rate limiting por tool/sesión y API key opcional en HTTP.

  • Sin dependencias de .NET instalado: se leen los ficheros, no se ejecuta MSBuild.

Related MCP server: dotnet-sherlock-mcp

Requisitos

  • Node.js >= 18.17.0

  • npm >= 9

Instalación

npm ci
npm run build

Configuración

Copia .env.example a .env y ajusta PROJECT_ROOT:

cp .env.example .env

Variable

Por defecto

Descripción

PROJECT_ROOT

— (obligatoria)

Ruta absoluta de la carpeta que contiene la .sln/.slnx.

MCP_TRANSPORT

stdio

stdio o http.

HOST

127.0.0.1

127.0.0.1, ::1, localhost o 0.0.0.0.

PORT

3001

Puerto en modo HTTP.

CACHE_TTL_SECONDS

60

TTL de .csproj y resources. 0 desactiva la caché.

LOG_LEVEL

info

error, warn, info o debug.

MAX_RESULTS

500

Tope por defecto de limit.

METRICS_ENABLED

true

Expone GET /stats.

RATE_LIMIT_PER_MINUTE

120

Límite por tool y sesión. 0 lo desactiva.

SESSION_TTL_SECONDS

1800

Vida de una sesión HTTP inactiva.

MAX_BODY_BYTES

1048576

Tamaño máximo de una petición HTTP.

MCP_API_KEY

—

Si se define, HTTP exige cabecera x-api-key.

REDACT_SECRETS

false

Enmascara contraseñas, claves y tokens en read_file/search_text.

RATE_LIMIT_STORE

—

Fichero JSON donde persiste el rate limit entre reinicios.

OAUTH_ISSUER

—

Activa OAuth: emisor esperado del bearer token.

OAUTH_AUDIENCE

—

Audiencia esperada del token.

OAUTH_JWKS_URI

<issuer>/.well-known/jwks.json

JWKS para validar la firma.

OTEL_EXPORTER_OTLP_ENDPOINT

—

Exporta trazas por OTLP/HTTP (spans por tool).

Ejecución

npm run build
npm start                 # respeta MCP_TRANSPORT del .env

Modo HTTP:

MCP_TRANSPORT=http PORT=3001 node dist/server/index.js
# GET    /health  -> {"status":"ok"}            (sin auth, para probes)
# GET    /ready   -> configuración + sesiones activas
# GET    /stats   -> métricas por tool y tokens (JSON)
# GET    /metrics -> las mismas métricas en formato Prometheus
# GET    /.well-known/oauth-protected-resource -> metadata OAuth (si OAUTH_ISSUER está definido)
# POST   /mcp     -> initialize / tools / resources / prompts
# GET    /mcp     -> stream SSE de la sesión
# DELETE /mcp     -> cierra la sesión

La primera petición initialize devuelve Mcp-Session-Id; las siguientes lo reutilizan. Una sesión desconocida responde 404 y una inactiva se cierra sola al expirar SESSION_TTL_SECONDS.

Modo STDIO (por defecto): el proceso habla MCP por stdin/stdout y escribe todos los logs por stderr, así que el stream JSON-RPC nunca se corrompe.

Conectar un agente

Claude Code / Claude Desktop

{
  "mcpServers": {
    "mcp-visual": {
      "command": "node",
      "args": ["C:/ruta/a/mcp-visual/dist/server/index.js"],
      "env": { "PROJECT_ROOT": "C:/ruta/a/MiSolucion" }
    }
  }
}

VS Code (.vscode/mcp.json)

{
  "servers": {
    "mcp-visual": {
      "type": "stdio",
      "command": "node",
      "args": ["C:/ruta/a/mcp-visual/dist/server/index.js"],
      "env": { "PROJECT_ROOT": "C:/ruta/a/MiSolucion" }
    }
  }
}

Cliente HTTP / web

{ "url": "http://127.0.0.1:3001/mcp", "headers": { "x-api-key": "tu-clave" } }

Herramientas

Todas las listas aceptan limit (máximo de elementos) y offset, y devuelven total, returned, truncated y nextOffset.

Herramienta

Entrada

Devuelve

get_solution

solutionPath?, limit?, offset?, view?

Solución + proyectos enriquecidos.

list_projects

solutionPath?, limit?, offset?

Proyectos con el mismo formato.

get_project

projectPath, view?

Metadatos del .csproj y sus referencias.

list_project_files

projectPath, limit?, offset?

Ficheros del proyecto (sin bin/obj).

get_project_references

projectPath, kind?, limit?, offset?

Referencias project/package/assembly.

get_project_targets

projectPath

Target frameworks y output type.

get_project_dependencies

projectPaths[]

Grafo proyecto → referencias.

analyze_project

projectPath?, limit?

Resumen, issues y recomendaciones.

resolve_asset_paths

directory?, limit?, offset?

Assets estáticos.

list_solutions

directory?, limit?, offset?

Todas las .sln/.slnx (monorepos).

read_file

path, startLine?, maxLines?

Ventana de líneas y total del fichero.

search_text

query, directory?, caseSensitive?, limit?, offset?

Coincidencias con fichero y línea.

search_symbols

query?, kind?, directory?, limit?, offset?

Clases, interfaces, métodos y propiedades con fichero y línea.

open_solution

solutionPath?

Abre la solución en Visual Studio y devuelve el PID.

view: "summary" recorta la respuesta a lo esencial (menos tokens por llamada).

open_solution es la única herramienta con efectos: localiza Visual Studio con vswhere, confina la solución a PROJECT_ROOT y lanza devenv.exe en modo detached. Sin Visual Studio devuelve IDE_NOT_FOUND.

Resources

Lectura estática y cacheable, separada de las acciones. Cada resource lleva _meta.etag para detectar cambios sin volver a transferir el contenido.

URI

Contenido

mcp://solution

Solución raíz y sus proyectos (resumen).

mcp://projects

Proyectos con metadatos de build.

mcp://solutions

Todas las soluciones del workspace.

mcp://assets

Assets estáticos.

mcp://file/{+path} (template)

Contenido de un fichero (hasta 2000 líneas).

resources/list pagina con cursor/nextCursor. Los ficheros se exponen como template para no inundar el contexto con miles de entradas en un monorepo.

resources/subscribe está soportado: el servidor observa PROJECT_ROOT (recursivo, con debounce) y emite notifications/resources/updated para las URIs suscritas cuando algo cambia.

Prompts

Plantillas del servidor, tipadas y versionadas (_meta.version), en lugar de prompts hardcodeados en el cliente.

Prompt

Argumentos

review_project

projectPath (obligatorio), focus?

find_todos

directory?, marker? (TODO|FIXME|HACK)

explain_dependencies

projectPaths[] (obligatorio)

Un prompt no gasta contexto por sí mismo: instruye al agente sobre qué tools llamar y con qué forma.

completion/complete autocompleta projectPath, projectPaths, solutionPath, directory y el marker de find_todos con datos reales del workspace.

Errores

Dos niveles, ambos sin stack traces hacia el modelo:

  • Protocolo (JSON-RPC): -32602 argumentos inválidos (con data.details por campo), -32601 tool/prompt desconocido, -32000 rate limit (data.retryAfterMs), -32603 fallo interno.

  • Ejecución de tool: isError: true con { "error": { "code", "message", "data?" } }.

Códigos de dominio: MISSING_PROJECT_ROOT, INVALID_PROJECT_ROOT, SOLUTION_NOT_FOUND, PATH_TRAVERSAL, CSPROJ_PARSER_ERROR, TEXT_READER_ERROR, FILE_SCANNER_ERROR, INVALID_TOOL_ARGUMENT, UNKNOWN_TOOL, RESOURCE_NOT_FOUND, RATE_LIMITED, IDE_NOT_FOUND.

Arquitectura

src/
├── domain/            # Modelos y puertos. Sin I/O, sin frameworks.
│   ├── models/        # project-types, project, csprojfile, solution, dependencygraph, fileentry, analysisreport
│   ├── services/      # solution-reader, csproj-parser, dependency-analyzer, file-scanner,
│   │                  # path-resolver, text-reader, ide-launcher
│   └── errors/        # DomainError (message, code, data)
├── application/       # Casos de uso + DTOs + paginación. Solo depende de domain.
│   ├── use-cases/     # 13 casos de uso, uno por capacidad
│   ├── dtos/          # project-summary, solution-summary
│   └── pagination.ts  # limit/offset/nextOffset compartido
├── infrastructure/    # Adaptadores concretos de los puertos.
│   ├── fs/            # LogicalFs, NodeFsAdapter, PhysicalPathResolver
│   ├── io/            # NodeTextReader, FastXmlParser, CacheAdapter
│   ├── caching/       # CachedCsprojParser (decorator TTL)
│   ├── logging/       # ConsoleLogger (stderr, niveles, meta JSON)
│   ├── metrics/       # InMemoryMetrics (latencia, tokens) + Prometheus
│   ├── msbuild/       # MSBuildPropsResolver (props, imports, versiones centrales)
│   ├── auth/          # OAuthTokenVerifier (JWKS)
│   ├── otel/          # OtlpHttpTracer (trazas sin SDK)
│   ├── ratelimit/     # JsonRateLimitStore
│   ├── watch/         # NodeChangeWatcher (resources/subscribe)
│   ├── ide/           # VisualStudioLauncher (vswhere + devenv)
│   └── services/      # NodeSolutionReader, NodeCsprojParser, NodeFileScanner, NodeDependencyAnalyzer
├── presentation/
│   ├── mcp/
│   │   ├── itool.ts            # ITool + ToolContext + JSON Schema desde Zod
│   │   ├── tool-registry.ts    # registro explícito + validación
│   │   ├── tools/              # 14 clases, una por tool
│   │   ├── resources/          # IResource, registry con cursor/caché/ETag, 5 resources
│   │   ├── prompts/            # IPrompt, registry, 3 prompts versionados
│   │   ├── completions.ts      # autocompletado con datos del workspace
│   │   ├── subscriptions.ts    # bookkeeping de resources/subscribe
│   │   ├── errors/             # DomainError → McpError / payload de tool
│   │   └── server.ts           # handlers MCP + middleware de errores y métricas
│   ├── http/                   # Streamable HTTP con sesiones, auth, /stats, /metrics, OAuth
│   └── stdio/                  # StdioServerTransport
├── shared/            # asset-config, logger, metrics, tokens, rate-limiter, redact, tracer
├── composition-root.ts# Único lugar donde se eligen los adaptadores
└── server/index.ts    # Bootstrap: env, config, transporte, graceful shutdown

Principios aplicados:

  • S — una clase por tool, un registry por tipo de primitiva, un caso de uso por capacidad.

  • O — añadir una tool es añadir una clase y registrarla; ni el servidor ni los transportes cambian.

  • L — CachedCsprojParser y los adaptadores de LogicalFs sustituyen a los originales.

  • I — puertos pequeños (TextReader, FileScanner, IdeLauncher, Metrics…).

  • D — domain/application dependen de interfaces; el composition root inyecta lo concreto, sin service locator ni reflexión.

Scripts

npm run typecheck   # tsc --noEmit
npm test            # Jest (unitarias + integración de tools/resources/prompts)
npm run build       # dist/
npm run verify      # typecheck + test + build
npm start           # servidor compilado

Las pruebas de integración usan un fixture .NET versionado en test/fixtures/workspace.

Limitaciones conocidas

  • No ejecuta MSBuild: no resuelve imports de Directory.Build.props ni paquetes transitivos reales.

  • El grafo de dependencias es directo (proyecto → referencias declaradas), sin detección de ciclos.

  • Los assets se detectan por carpeta y extensión; no se interpretan ItemGroup/Content.

  • search_symbols es declarativo (regex), no un parser Roslyn: no resuelve genéricos complejos, partial repartidos ni sobrecargas por firma.

  • Los paquetes transitivos son los alcanzables por referencias de proyecto; no se expande el grafo de dependencias de cada paquete NuGet (requiere restore).

  • OAuth valida firmas con JWKS, pero no implementa el servidor de autorización ni tasks de larga duración.

  • OpenTelemetry exporta trazas; las métricas se exponen en /metrics, no por OTLP.

  • No se usa sampling: el servidor no necesita un LLM para analizar código.

  • Si tools/call llega con arguments que no es un objeto, el SDK rechaza la petición antes del servidor con -32603 y un mensaje de Zod verboso; es limitación de @modelcontextprotocol/sdk.

Licencia

MIT — ver LICENSE.

Available Tools

14 tools
analyze_projectAnalyze projectC

Returns a structured report with line counts and TODO/FIXME markers.

Inputs: limit, projectPath. Returns: object

get_projectGet projectB

Returns one project's kind, target framework, output type and references.

Inputs: projectPath (required), view. Returns: object

get_project_dependenciesGet project dependenciesC

Builds the dependency graph that starts at the given projects.

Inputs: projectPaths (required). Returns: object

get_project_referencesGet project referencesB

Returns the project, package and assembly references of a project.

Inputs: projectPath (required), kind, limit, offset. Returns: object

get_project_targetsGet project targetsB

Returns the target frameworks and output type of a project.

Inputs: projectPath (required). Returns: object

get_solutionGet solutionC

Returns the solution and the projects it declares.

Inputs: view, limit, offset, solutionPath. Returns: object

list_project_filesList project filesC

Lists the source and configuration files of a project.

Inputs: projectPath (required), limit, offset. Returns: object

list_projectsList projectsB

Lists the projects declared by the solution, with metadata.

Inputs: limit, offset, solutionPath. Returns: object

list_solutionsList solutionsA

Lists every .sln/.slnx in the workspace (monorepos).

Inputs: limit, offset, directory. Returns: object

open_solutionOpen in Visual StudioB

Launches Visual Studio with a workspace solution (starts a GUI process).

Inputs: solutionPath. Returns: object

read_fileRead fileA

Reads a workspace file, optionally a window of lines, with the total count.

Inputs: path (required), maxLines, startLine. Returns: object

resolve_asset_pathsResolve asset pathsC

Lists the static assets (images, styles, fonts, media) of the workspace.

Inputs: limit, offset, directory. Returns: object

search_symbolsSearch symbolsB

Finds C# type, method and property declarations with file and line.

Inputs: kind, limit, query, offset, +1 more. Returns: object

search_textSearch textA

Searches literal text across the source files of the workspace.

Inputs: query (required), limit, offset, directory, +1 more. Returns: object

Tool Schema Changelog

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

Loading tool schema changelog…

    TDQS

    B3.2/5.0

    Scored across 14 tools

    Disambiguation3/5

    Several tools have overlapping boundaries: get_project already returns target framework, output type, and references, which overlaps heavily with get_project_targets and get_project_references. Similarly, get_solution returns the projects declared by the solution while list_projects also lists those projects, making selection less obvious.

    Naming Consistency5/5

    All tool names use a consistent snake_case verb_noun pattern, such as get_project, list_projects, search_symbols, and read_file. The convention is predictable throughout the set.

    Tool Count4/5

    The set has 14 tools, which is reasonable for solution/project inspection and search. However, a few specialized getters duplicate information already available from broader tools, making the count slightly heavier than necessary.

    Completeness4/5

    The surface covers solution/project discovery, metadata, references, dependencies, targets, files, searches, assets, and analysis, which is strong for a read-only inspection server. Minor gaps exist around build/compile operations or solution lifecycle management beyond opening a solution.

    Maintenance

    ActivityMaintained
    ResponsivenessNo recent community issues

    Related MCP Connectors

    Related MCP Servers

    • A
      license
      A
      quality
      B
      maintenance
      A Model Context Protocol (MCP) server providing 62 AI-optimized tools for .NET/C# semantic code analysis, navigation, refactoring, and code generation using Microsoft Roslyn. Built for AI coding agents - provides compiler-accurate code understanding that AI cannot infer from reading source files alone.
      62
      41
      MIT
    • A
      license
      Not graded
      quality
      B
      maintenance
      ILSpy for LLM coding agents. Reflection-based MCP server with 31+ tools to explore .NET assemblies, NuGet packages, types, members, attributes, and XML docs.
      10
      MIT
    • A
      license
      Not graded
      quality
      D
      maintenance
      Enables AI clients to perform local code search, indexing, and analysis across Java, JavaScript/TypeScript, .NET/C#, and Python projects through the MCP protocol.
      1
      Apache 2.0
    • A
      license
      A
      quality
      C
      maintenance
      MCP server for .NET assembly analysis. Vendor-neutral wrapper around AsmResolver and ILSpy for parsing and decompiling .NET assemblies.
      11
      1
      MIT