Skip to main content
Glama
rkirkendall

Medplum MCP Server

by rkirkendall

createEpisodeOfCare

Create and manage a patient's episode of care, specifying the patient ID, status, and optionally, the managing organization, using Medplum's MCP Server for healthcare data operations.

Instructions

Creates a new episode of care for a patient. Requires patient ID and status.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
managingOrganizationIdNoThe ID of the organization managing this episode. Optional.
patientIdYesThe ID of the patient this episode of care is for.
statusYesThe status of the episode of care.

Implementation Reference

  • Implements the core logic for creating an EpisodeOfCare FHIR resource using the Medplum client, including validation, resource construction, and error handling.
    export async function createEpisodeOfCare(
      args: CreateEpisodeOfCareArgs,
      client?: MedplumClient,
    ): Promise<EpisodeOfCare | OperationOutcome> {
      const medplumClient = client || medplum;
      await ensureAuthenticated();
      try {
        if (!args.patientId) {
          throw new Error('Patient ID is required to create an EpisodeOfCare.');
        }
        if (!args.status) {
          throw new Error('Status is required to create an EpisodeOfCare.');
        }
    
        const episode: EpisodeOfCare = {
          resourceType: 'EpisodeOfCare',
          status: args.status,
          patient: { reference: `Patient/${args.patientId}` },
          type: args.type,
          identifier: args.identifier,
          period: args.periodStart || args.periodEnd ? {
            start: args.periodStart,
            end: args.periodEnd,
          } : undefined,
          managingOrganization: args.managingOrganizationId
            ? { reference: `Organization/${args.managingOrganizationId}` }
            : undefined,
          careManager: args.careManagerId
            ? { reference: `Practitioner/${args.careManagerId}` }
            : undefined,
          // team: args.teamMemberIds?.map(id => ({ reference: `CareTeam/${id}` })) // If using CareTeam IDs
        };
    
        // Remove undefined top-level fields to keep the resource clean
        Object.keys(episode).forEach((key) => (episode as any)[key] === undefined && delete (episode as any)[key]);
        if (episode.period && !episode.period.start && !episode.period.end) {
          delete episode.period;
        }
    
        const result = (await medplumClient.createResource(episode)) as EpisodeOfCare;
        console.log('EpisodeOfCare created successfully:', result.id);
        return result;
      } catch (error: any) {
        const outcome: OperationOutcome = {
          resourceType: 'OperationOutcome',
          issue: [
            {
              severity: 'error',
              code: 'exception',
              diagnostics: `Error creating EpisodeOfCare: ${error.message || 'Unknown error'}`,
            },
          ],
        };
        if (error.outcome) {
          return error.outcome as OperationOutcome;
        }
        return outcome;
      }
    }
  • Defines the JSON schema for input validation of the createEpisodeOfCare tool, including parameters like patientId, status, and optional fields.
    {
      name: 'createEpisodeOfCare',
      description: 'Creates a new EpisodeOfCare for a patient. Requires patient ID and status.',
      input_schema: {
        type: 'object',
        properties: {
          patientId: { type: 'string', description: "The ID of the patient for whom this episode of care is being created." },
          status: { 
            type: 'string', 
            description: "The status of the episode of care.",
            enum: ['planned', 'waitlist', 'active', 'onhold', 'finished', 'cancelled', 'entered-in-error']
          },
          managingOrganizationId: { type: 'string', description: "Optional. ID of the organization managing this episode of care." },
          careManagerId: { type: 'string', description: "Optional. ID of the practitioner who is the care manager for this episode." },
          type: {
            type: 'array',
            items: {
              type: 'object',
              properties: {
                coding: {
                  type: 'array',
                  items: {
                    type: 'object',
                    properties: {
                      system: { type: 'string', description: "The URI for the coding system (e.g., 'http://terminology.hl7.org/CodeSystem/episodeofcare-type')." },
                      code: { type: 'string', description: "The code from the coding system (e.g., 'hacc')." },
                      display: { type: 'string', description: "Optional. The display name for the code." }
                    },
                    required: ['system', 'code']
                  }
                },
                text: { type: 'string', description: "Optional. Plain text representation of the type." }
              },
              // required: ['coding'] // A type can be just text
            },
            description: "Optional. Type of episode of care, e.g., Home and Community Care. Provide an array of CodeableConcept objects."
          },
          periodStart: { type: 'string', format: 'date-time', description: "Optional. The start date/time of the episode of care (ISO8601 format)." },
          periodEnd: { type: 'string', format: 'date-time', description: "Optional. The end date/time of the episode of care (ISO8601 format)." },
          identifier: {
            type: 'array',
            items: {
              type: 'object',
              properties: {
                system: { type: 'string', description: "The system for the identifier (e.g., 'urn:oid:1.2.3.4.5')." },
                value: { type: 'string', description: "The value of the identifier." }
              },
              required: ['value']
            },
            description: "Optional. One or more identifiers for this episode of care."
          }
        },
        required: ['patientId', 'status']
      }
    },
  • src/index.ts:714-736 (registration)
    Registers the createEpisodeOfCare tool in the MCP server by including its schema in the mcpTools array used for list tools request.
    {
      name: "createEpisodeOfCare",
      description: "Creates a new episode of care for a patient. Requires patient ID and status.",
      inputSchema: {
        type: "object",
        properties: {
          patientId: {
            type: "string",
            description: "The ID of the patient this episode of care is for.",
          },
          status: {
            type: "string",
            description: "The status of the episode of care.",
            enum: ["planned", "waitlist", "active", "onhold", "finished", "cancelled", "entered-in-error"],
          },
          managingOrganizationId: {
            type: "string",
            description: "The ID of the organization managing this episode. Optional.",
          },
        },
        required: ["patientId", "status"],
      },
    },
  • src/index.ts:979-979 (registration)
    Maps the tool name to its handler function in the toolMapping object used by the MCP call tool request handler.
    createEpisodeOfCare,
  • TypeScript interface defining the arguments for the createEpisodeOfCare function, used for type safety in the handler.
    export interface CreateEpisodeOfCareArgs {
      patientId: string;
      status: EpisodeOfCareStatus; // planned | waitlist | active | onhold | finished | cancelled | entered-in-error
      managingOrganizationId?: string;
      type?: CodeableConcept[]; // e.g., [{ coding: [{ system: 'http://terminology.hl7.org/CodeSystem/episodeofcare-type', code: 'hacc' }]}] (Home and Community Care)
      periodStart?: string; // ISO8601 DateTime
      periodEnd?: string; // ISO8601 DateTime
      careManagerId?: string; // ID of the Practitioner
      teamMemberIds?: string[]; // IDs of CareTeam resources (more complex, consider if needed for initial version)
      identifier?: Identifier[];
      // diagnosis related fields are complex (condition, role, rank) - might simplify or add later
    }
Behavior2/5

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

No annotations are provided, so the description carries the full burden of behavioral disclosure. It states 'Creates a new episode of care,' implying a write operation, but does not cover critical aspects like authentication needs, error handling, rate limits, or what happens upon success (e.g., returns an ID). For a creation tool with zero annotation coverage, this is a significant gap in transparency.

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 concise with two sentences that directly address purpose and requirements. It is front-loaded with the main action. However, it could be slightly more structured by explicitly listing parameters or including usage context, but it avoids unnecessary verbosity.

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's complexity (creation operation with 3 parameters), lack of annotations, and no output schema, the description is incomplete. It does not explain behavioral traits, return values, or error conditions. While the schema covers parameters well, the overall context for safe and effective use is insufficient, especially for a write tool in a FHIR environment.

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%, so the schema fully documents all parameters (patientId, status, managingOrganizationId). The description adds minimal value by mentioning 'Requires patient ID and status,' which restates schema requirements without providing additional semantic context (e.g., format of IDs, meaning of statuses). Baseline 3 is appropriate as the schema does the heavy lifting.

Input schemas describe structure but not intent. Descriptions should explain non-obvious parameter relationships and valid value ranges.

Purpose4/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: 'Creates a new episode of care for a patient.' It specifies the verb ('creates') and resource ('episode of care'), but does not explicitly differentiate it from sibling tools like 'createPatient' or 'createEncounter', which also create FHIR resources. The mention of 'patient' provides some context, but a more specific distinction would elevate this to a 5.

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 minimal guidance: 'Requires patient ID and status.' This indicates required parameters but does not explain when to use this tool versus alternatives like 'createEncounter' or 'updateEpisodeOfCare'. No context on prerequisites, exclusions, or typical workflows is given, leaving the agent with little direction on appropriate usage scenarios.

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

Install Server

Other Tools

Related Tools

Latest Blog Posts

MCP directory API

We provide all the information about MCP servers via our MCP API.

curl -X GET 'https://glama.ai/api/mcp/v1/servers/rkirkendall/medplum-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server