Skip to main content
Glama

clinic-mcp

Un servidor de referencia del Model Context Protocol para la programación y admisión en clínicas. Construido en TypeScript con tipado estricto, errores estructurados y aislamiento de inquilinos aplicado en la capa de datos. Los datos son sintéticos. Esto no es software clínico.

El objetivo es mostrar cómo se ve un servidor MCP con formato de producción para un sector que exige aislamiento de datos y resultados fundamentados: la misma forma de código que escribo en Rentive, con datos simulados y un dominio diferente para que los patrones sean revisables sin filtrar nada propietario.

Por qué MCP

Las aplicaciones LLM siguen reinventando el mismo cableado: definiciones de funciones ad-hoc por proveedor, análisis de argumentos a medida, sin transporte compartido, sin un modelo de error consistente. MCP es un pequeño protocolo abierto que soluciona la capa de cableado. Un servidor expone una lista de herramientas tipadas sobre stdio (o HTTP), y cualquier cliente compatible con MCP (Claude Desktop, integraciones de IDE, agentes personalizados) puede descubrirlas y llamarlas con el mismo mecanismo.

Para los backends de dominio, eso significa que escribes las herramientas una vez y funcionan en todas partes. Para los creadores de agentes, significa que dejas de crear esquemas de herramientas manualmente y empiezas a componer servidores.

Related MCP server: tenant-scoped-crm

Arquitectura

flowchart LR
    Client["MCP client<br/>(Claude Desktop, custom agent)"]
    Server["clinic-mcp server"]
    Tools["Tools<br/>find_available_slot<br/>book_appointment<br/>record_intake<br/>search_protocols<br/>escalate_to_oncall"]
    Store["ClinicStore<br/>tenant-scoped accessors"]
    Seed[("seed.json<br/>synthetic clinics, providers,<br/>patients, protocols")]

    Client -->|stdio JSON-RPC| Server
    Server --> Tools
    Tools --> Store
    Store --> Seed

Cada herramienta toma un clinic_id y el almacén garantiza que todas las lecturas y escrituras estén limitadas a esa clínica. El acceso entre inquilinos lanza un TenantMismatchError en lugar de devolver silenciosamente la fila incorrecta. Esto refleja el patrón de seguridad a nivel de fila que una implementación de producción aplicaría en Postgres, expuesto aquí en el código de la aplicación para que la garantía sea revisable en un solo archivo (src/store/index.ts).

Ejecutarlo localmente

Requiere Node 20+ y pnpm.

git clone https://github.com/dominikstefanski/clinic-mcp.git
cd clinic-mcp
pnpm install
pnpm test          # 29 tests
pnpm typecheck
pnpm dev           # boots the server on stdio

El servidor lee src/store/seed.json al iniciarse y sirve dos clínicas sintéticas: clinic_north (medicina general, cardiología, dermatología) y clinic_west (pediatría, medicina general).

Conectar a Claude Desktop

Añade esto a tu configuración de Claude Desktop (macOS: ~/Library/Application Support/Claude/claude_desktop_config.json). Reemplaza la ruta con tu clon local.

{
  "mcpServers": {
    "clinic-mcp": {
      "command": "npx",
      "args": ["-y", "tsx", "/absolute/path/to/clinic-mcp/src/server.ts"]
    }
  }
}

Reinicia Claude Desktop. Las cinco herramientas aparecerán en el menú de conexiones. Prueba un prompt como "Busca una cita de medicina general en clinic_north el próximo lunes por la mañana."

Referencia de herramientas

Todas las herramientas devuelven { ok: true, ...result } en caso de éxito o { ok: false, error: { code, message } } en caso de error. Las entradas se validan con zod; los errores de argumentos a nivel de MCP se devuelven como errores de validation con detalles del campo.

find_available_slot

Busca espacios de cita disponibles para una especialidad en un rango de fechas, omitiendo conflictos.

Campo

Tipo

Notas

clinic_id

string

Requerido

specialty

enum

general_practice

pediatrics

cardiology

dermatology

from_iso

string

ISO 8601 de inicio inclusivo

to_iso

string

ISO 8601 de fin exclusivo

duration_minutes

int

15 a 120, predeterminado 30

limit

int

1 a 50, predeterminado 10

book_appointment

Crea una cita. Requiere una idempotency_key proporcionada por el llamador; las repeticiones devuelven la cita original en lugar de reservar doble. Los agentes de voz reintentarán, por lo que esto no es opcional.

Campo

Tipo

Notas

clinic_id

string

Requerido

provider_id

string

Debe pertenecer a clinic_id

patient_id

string

Debe pertenecer a clinic_id

start_iso

string

ISO 8601

duration_minutes

int

15 a 120, predeterminado 30

reason

string

1 a 500 caracteres

idempotency_key

string

8 a 128 caracteres, proporcionado por el llamador

Devuelve { appointment, idempotent_replay }.

record_intake

Persiste una nota de admisión estructurada y asigna un nivel de triaje.

Campo

Tipo

Notas

clinic_id

string

Requerido

patient_id

string

Debe pertenecer a clinic_id

symptoms

string[]

1 a 20 entradas

severity

int

1 a 10, reportado por el paciente

onset_iso

string

ISO 8601

notes

string

Opcional, máx 2000 caracteres

Regla de triaje: severidad >= 8 es urgent, >= 5 es elevated, de lo contrario routine.

search_protocols

Búsqueda por palabras clave en la biblioteca de protocolos de la clínica. Devuelve fragmentos clasificados que el modelo puede citar al responder.

Campo

Tipo

Notas

clinic_id

string

Requerido

query

string

1 a 500 caracteres

limit

int

1 a 20, predeterminado 5

La implementación actual es una puntuación TF ingenua con ponderación de título (3x). Existe para demostrar la interfaz de una herramienta de recuperación; las implementaciones de producción cambiarían el backend por una búsqueda vectorial (ver notas de diseño).

escalate_to_oncall

Marca una cita existente como urgente y la reasigna al proveedor de guardia de la clínica.

Campo

Tipo

Notas

clinic_id

string

Requerido

appointment_id

string

Debe pertenecer a clinic_id

reason

string

1 a 500 caracteres, añadidos a la razón de la cita

Devuelve { appointment, on_call_provider, reassigned }.

Notas de diseño

El aislamiento de inquilinos se aplica en el almacén, no en la herramienta. Las herramientas aceptan un clinic_id y lo pasan hacia abajo. El almacén valida la propiedad en cada acceso y lanza un TenantMismatchError en caso de discrepancia. Si añades una nueva herramienta mañana, no puedes filtrar accidentalmente entre clínicas; el almacén no te lo permitirá.

Idempotencia en las escrituras. book_appointment requiere una idempotency_key. Los llamadores reales (agentes de voz, bucles de reintento, fallos de red) repetirán las solicitudes, y un sistema de salud que responde a los reintentos creando citas duplicadas es un sistema de salud que pierde la confianza desde el primer día.

Errores estructurados en lugar de cadenas lanzadas. Cada fallo de dominio es una subclase de DomainError tipada con un code estable. El envoltorio MCP los convierte en { ok: false, error: { code, message } }. Los clientes pueden ramificarse según el code en lugar de usar expresiones regulares en el message.

La herramienta de recuperación es un sustituto. search_protocols utiliza una puntuación TF en memoria para que el repositorio se ejecute sin servicios externos. En producción, esta es la unión donde conectarías Pinecone, pgvector o tu backend de recuperación preferido. El contrato de entrada/salida de la herramienta permanece igual.

El manejo del tiempo está simplificado. Los horarios de trabajo de los proveedores se interpretan en UTC para mayor claridad. Una implementación real respetaría la zona horaria de cada clínica (ya incluida en el esquema). Menciono esto explícitamente para que los revisores sepan que es intencional, no un descuido.

Lo que esto no es

  • No es software clínico. La regla de triaje es un juguete y el corpus de protocolos es prosa escrita a mano. No lo uses para nada que involucre a pacientes reales.

  • No cumple con HIPAA. Los datos son falsos, el almacenamiento es en memoria, no hay registro de auditoría. La producción necesitaría todo eso y más.

  • No es un EMR completo ni un backend de programación. El objetivo es mostrar la forma de un servidor MCP, no lanzar un sistema clínico.

Licencia

MIT. Ver LICENSE.

Available Tools

5 tools
book_appointmentBook an appointmentB

Create an appointment for a patient with a provider. Requires an idempotency_key; repeated calls with the same key return the original appointment instead of double-booking.

NameRequiredDescriptionDefault
clinic_idYes
provider_idYes
patient_idYes
start_isoYesAppointment start, ISO 8601
duration_minutesNo
reasonYes
idempotency_keyYesCaller-supplied key. Repeated calls with the same key return the original appointment instead of double-booking.

TDQS

B3.3/5.0
Behavior3/5

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

With no annotations, the description carries full burden. It discloses idempotency behavior (returns original on repeat), which is useful for safe retries, but omits other behavioral traits like required permissions, side effects, or error states.

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: one states the core purpose, the other adds critical idempotency detail. No wasted words.

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

Completeness2/5

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

Given the tool has 7 parameters, no output schema, and zero annotations, the description is incomplete. It does not explain return value, error handling, or scheduling constraints like business hours.

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

Parameters2/5

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

Schema description coverage is only 29% (2/7 params described). The description does not add meaning for undocumented parameters (e.g., clinic_id, provider_id, patient_id, duration_minutes, reason) beyond their names, failing to compensate for low coverage.

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 that the tool creates an appointment for a patient with a provider, distinguishing it from sibling tools like find_available_slot (which finds slots) and record_intake (which records intake).

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

Usage Guidelines2/5

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

The description does not provide guidance on when to use this tool versus alternatives like find_available_slot, nor does it specify prerequisites or exclusions.

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

escalate_to_oncallEscalate an appointment to the on-call providerC

Mark an existing appointment as urgent and reassign it to the clinic's on-call provider.

NameRequiredDescriptionDefault
clinic_idYes
appointment_idYes
reasonYes

TDQS

C2.9/5.0
Behavior2/5

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

No annotations provided, so description carries full burden. It only states 'mark as urgent and reassign' without detailing side effects (e.g., notifications, status changes) or reversibility.

Agents need to know what a tool does to the world before calling it. Descriptions should go beyond structured annotations to explain consequences.

Conciseness3/5

Is the description appropriately sized, front-loaded, and free of redundancy?

Single sentence is efficient but omits critical details; adequate but could include a brief second sentence without losing conciseness.

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

Completeness2/5

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

Lacks output description and any mention of consequences or constraints (e.g., irreversibility), leaving the agent uninformed for correct invocation.

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

Parameters2/5

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

Schema coverage is 0%, and description adds no parameter details beyond names. 'reason' is not explained as the reason for urgency; clinic_id/appointment_id are self-evident but lack any validation context.

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 action ('mark as urgent and reassign') and resource ('existing appointment'), and clearly distinguishes from sibling tools like book_appointment or find_available_slot.

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

Usage Guidelines2/5

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

The description provides no guidance on when to use this tool vs alternatives, no prerequisites (e.g., appointment must exist), and no conditions to avoid (e.g., already escalated).

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

find_available_slotFind available appointment slotsB

Return open appointment slots for a given specialty in a date range. Filters by clinic_id and skips conflicts with existing appointments.

NameRequiredDescriptionDefault
clinic_idYes
specialtyYes
from_isoYesInclusive start of the search window, ISO 8601
to_isoYesExclusive end of the search window, ISO 8601
duration_minutesNo
limitNo

TDQS

B3.4/5.0
Behavior3/5

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

With no annotations, the description carries full burden. It discloses that it 'skips conflicts with existing appointments,' indicating a read-only, availability-checking behavior. However, it does not mention whether it requires authentication, whether it is idempotent, or any side effects. The behavioral disclosure is partial but not misleading.

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 the main action. Every word serves a purpose: what it returns, the key filters, and the conflict avoidance. No fluff.

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

Completeness2/5

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

Despite moderate complexity (6 params, no output schema), the description omits important details: return format (list of slot times?), ordering, pagination, error conditions. The sibling 'book_appointment' suggests a workflow, but no linkage is provided. The description is too sparse for complete agent understanding.

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 low (33%, only from/to have descriptions). The description adds meaning for specialty and date range, and mentions clinic_id filtering. But it does not explain duration_minutes or limit parameters. Given low coverage, the description partially compensates but leaves gaps.

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?

Description clearly states 'Return open appointment slots' with specific constraints ('given specialty in a date range', 'Filters by clinic_id'). This distinguishes it from sibling tools like 'book_appointment' (booking) and 'record_intake' (recording). The verb and resource are immediately clear.

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

Usage Guidelines2/5

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

The description does not provide any guidance on when to use this tool versus alternatives, such as before booking an appointment or when an immediate slot is needed. It describes what it does but lacks explicit context for selection among siblings.

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

record_intakeRecord patient intakeB

Persist a structured intake note (symptoms, severity, onset) for a patient and assign a triage level (routine / elevated / urgent).

NameRequiredDescriptionDefault
clinic_idYes
patient_idYes
symptomsYes
severityYesPatient-reported severity, 1 (mild) to 10 (worst imaginable)
onset_isoYesWhen symptoms began, ISO 8601
notesNo

TDQS

B3.1/5.0
Behavior2/5

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

No annotations; description only states it persists and assigns triage level, but fails to disclose side effects, authorization needs, or how triage is determined.

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?

Single sentence of 15 words, no redundancy, efficient and direct.

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

Completeness2/5

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

No output schema, no description of return value (e.g., triage level or record ID), insufficient to fully specify tool behavior.

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

Parameters2/5

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

Description mentions 'symptoms, severity, onset' but omits 'clinic_id', 'patient_id', and 'notes'. Schema coverage is 33%, leaving param gaps unaddressed.

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 action ('persist') and the resource ('structured intake note') with key fields, distinguishing it from sibling tools like 'book_appointment'.

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

Usage Guidelines2/5

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

No guidance on when to use this tool versus alternatives. No mention of prerequisites or exclusions.

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

search_protocolsSearch clinic protocol documentsB

Keyword search over the clinic's protocol library. Returns ranked snippets the model can cite when answering.

NameRequiredDescriptionDefault
clinic_idYes
queryYes
limitNo

TDQS

B3.3/5.0
Behavior3/5

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

Without annotations, the description carries full burden. It discloses that the tool returns ranked snippets that can be cited, which is informative, but lacks details on side effects, authentication, or rate limits. The behavior is adequately described for a simple read-only search.

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 extremely concise with two front-loaded sentences, each adding value: it states the action and the return format. No extraneous words.

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

Completeness2/5

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

Given the lack of output schema and parameter descriptions, the description is incomplete. It does not specify return structure beyond 'snippets', nor does it clarify the role of clinic_id. The tool requires more context for reliable use.

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

Parameters1/5

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

Schema description coverage is 0% and the description does not explain any parameters (clinic_id, query, limit). The agent must infer semantics solely from the parameter names and constraints, which is insufficient.

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 performs keyword search over the clinic's protocol library and returns ranked snippets for citation, making its purpose distinct from sibling tools that handle appointments, escalation, slot finding, and intake recording.

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?

The description implies usage for searching protocols via keyword, but does not provide explicit guidance on when to use this tool versus alternatives or when not to use it.

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. 5 tool updatesv0.1.0
    • First observedbook_appointment
    • First observedescalate_to_oncall
    • First observedfind_available_slot
    • First observedrecord_intake
    • First observedsearch_protocols

TDQS

A3.5/5.0

Scored across 5 tools

Disambiguation5/5

Each tool has a clearly distinct purpose: booking appointments, escalating to on-call, finding slots, recording intake, and searching protocols. No two tools overlap in functionality.

Naming Consistency5/5

All tool names follow a consistent verb_noun pattern in snake_case, making it easy to predict the action and resource for each tool.

Tool Count5/5

With exactly 5 tools, the server is well-scoped for a clinic domain, covering core patient-facing and administrative workflows without being overly heavy or thin.

Completeness3/5

The set covers appointment creation, urgent escalation, slot availability, intake recording, and protocol search. However, it lacks read/update/delete for appointments and any patient or provider management, which are notable gaps.

Maintenance

ActivityInactive
ResponsivenessOutdated data

Related MCP Connectors

Related MCP Servers

  • A
    license
    Not graded
    quality
    D
    maintenance
    A reference MCP server demonstrating safe agent access to multi-tenant CRM data with tenant isolation enforced in the data layer, role-based permissions, and human confirmation on writes.
    MIT
  • A
    license
    Not graded
    quality
    D
    maintenance
    An MCP server reference implementation adding enterprise layers (identity, authorization, audit) around MCP, with sample shipment status and delayed shipment tools over a stateless transport.
    Apache 2.0