Skip to main content
Glama
rkirkendall

Medplum MCP Server

by rkirkendall

updateEpisodeOfCare

Modify an existing healthcare episode by updating its status or other fields using its unique ID. Simplify data management in Medplum FHIR servers.

Instructions

Updates an existing episode of care. Requires the episode ID and fields to update.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
episodeOfCareIdYesThe unique ID of the episode of care to update.
statusNoNew status for the episode of care.

Implementation Reference

  • Core handler function that updates an EpisodeOfCare resource by reading the existing resource, applying partial updates to fields like status, type, period, managingOrganization, and careManager, then calling Medplum's updateResource.
    export async function updateEpisodeOfCare(
      episodeOfCareId: string,
      updates: UpdateEpisodeOfCareArgs,
      client?: MedplumClient,
    ): Promise<EpisodeOfCare | OperationOutcome> {
      const medplumClient = client || medplum;
      await ensureAuthenticated();
      try {
        if (!episodeOfCareId) {
          throw new Error('EpisodeOfCare ID is required for update.');
        }
        if (Object.keys(updates).length === 0) {
          throw new Error('No updates provided for EpisodeOfCare.');
        }
    
        // Fetch the existing resource
        const existingEpisode = await medplumClient.readResource('EpisodeOfCare', episodeOfCareId);
        if (!existingEpisode) {
          // This case should ideally be handled by readResource throwing a not-found error
          // which would be caught and returned as OperationOutcome or null by getEpisodeOfCareById logic
          // For robustness, if it somehow returns null here:
          return {
            resourceType: 'OperationOutcome',
            issue: [
              {
                severity: 'error',
                code: 'not-found',
                diagnostics: `EpisodeOfCare with ID "${episodeOfCareId}" not found for update.`,
              },
            ],
          };
        }
        
        // Construct the updated resource. Be careful with deep merges or partial updates.
        // A common strategy for utilities is to merge top-level fields or replace arrays.
        const resourceToUpdate: EpisodeOfCare = {
          ...existingEpisode,
          resourceType: 'EpisodeOfCare', // Ensure resourceType is maintained
          id: episodeOfCareId, // Ensure ID is maintained
        };
    
        if (updates.status) resourceToUpdate.status = updates.status;
        if (updates.type) resourceToUpdate.type = updates.type; // Replace array
        if (updates.managingOrganizationId) {
          resourceToUpdate.managingOrganization = { reference: `Organization/${updates.managingOrganizationId}` };
        } else if (updates.hasOwnProperty('managingOrganizationId') && updates.managingOrganizationId === null) {
            delete resourceToUpdate.managingOrganization; // Allow unsetting
        }
    
        if (updates.careManagerId) {
          resourceToUpdate.careManager = { reference: `Practitioner/${updates.careManagerId}` };
        } else if (updates.hasOwnProperty('careManagerId') && updates.careManagerId === null) {
            delete resourceToUpdate.careManager; // Allow unsetting
        }
    
        // Handle period update
        let periodUpdated = false;
        const currentPeriod = resourceToUpdate.period || {};
        const newPeriod: Period = { ...currentPeriod };
        if (updates.hasOwnProperty('periodStart')) {
          newPeriod.start = updates.periodStart; // Allow null/undefined to clear
          periodUpdated = true;
        }
        if (updates.hasOwnProperty('periodEnd')) {
          newPeriod.end = updates.periodEnd; // Allow null/undefined to clear
          periodUpdated = true;
        }
        if(periodUpdated){
            if(newPeriod.start || newPeriod.end){
                resourceToUpdate.period = newPeriod;
            } else {
                delete resourceToUpdate.period;
            }
        }
    
        // Remove undefined top-level fields from the merged object that might have been introduced by spread
        Object.keys(resourceToUpdate).forEach(
            (key) => (resourceToUpdate as any)[key] === undefined && delete (resourceToUpdate as any)[key]
        );
    
        const result = (await medplumClient.updateResource(resourceToUpdate)) as EpisodeOfCare;
        console.log('EpisodeOfCare updated successfully:', result.id);
        return result;
      } catch (error: any) {
         if (error.outcome && error.outcome.issue && error.outcome.issue[0]?.code === 'not-found') {
          return {
            resourceType: 'OperationOutcome',
            issue: [
              {
                severity: 'error',
                code: 'not-found',
                diagnostics: `EpisodeOfCare with ID "${episodeOfCareId}" not found for update.`,
              },
            ],
          };
        }
        const outcome: OperationOutcome = {
          resourceType: 'OperationOutcome',
          issue: [
            {
              severity: 'error',
              code: 'exception',
              diagnostics: `Error updating EpisodeOfCare: ${error.message || 'Unknown error'}`,
            },
          ],
        };
        if (error.outcome) {
          return error.outcome as OperationOutcome;
        }
        return outcome;
      }
    }
  • TypeScript interface defining the input arguments accepted by the updateEpisodeOfCare handler function.
    export interface UpdateEpisodeOfCareArgs {
      status?: EpisodeOfCareStatus;
      type?: CodeableConcept[];
      periodStart?: string;
      periodEnd?: string;
      managingOrganizationId?: string;
      careManagerId?: string;
      // Consider how to handle diagnosis updates - potentially replacing all, or adding/removing specific ones.
    }
  • JSON schema defining the input parameters and validation for the updateEpisodeOfCare tool.
      name: 'updateEpisodeOfCare',
      description: 'Updates an existing EpisodeOfCare. Requires the EpisodeOfCare ID and the fields to update.',
      input_schema: {
        type: 'object',
        properties: {
          episodeOfCareId: { type: 'string', description: 'The unique ID of the EpisodeOfCare to update.' },
          status: { 
            type: 'string', 
            description: "New status for the episode of care. Optional.",
            enum: ['planned', 'waitlist', 'active', 'onhold', 'finished', 'cancelled', 'entered-in-error']
          },
          type: { /* Same as in createEpisodeOfCare, optional */ type: 'array', items: { '$ref': '#/definitions/episodeOfCareTypeItem' }, description: "Optional. New list of types for the episode of care. This will replace the existing types." },
          periodStart: { type: 'string', format: 'date-time', description: "Optional. New start date/time (ISO8601)." },
          periodEnd: { type: 'string', format: 'date-time', description: "Optional. New end date/time (ISO8601)." },
          managingOrganizationId: { type: 'string', description: "Optional. New ID of the managing organization. Provide an empty string or null (if supported by LLM) to remove." },
          careManagerId: { type: 'string', description: "Optional. New ID of the care manager. Provide an empty string or null to remove." }
          // Diagnosis updates are complex and typically handled differently, so not included in simple updates.
        },
        required: ['episodeOfCareId'] // At least one update field is implicitly required
      }
    },
  • src/index.ts:752-769 (registration)
    MCP server tool registration including name, description, and input schema for updateEpisodeOfCare.
      name: "updateEpisodeOfCare",
      description: "Updates an existing episode of care. Requires the episode ID and fields to update.",
      inputSchema: {
        type: "object",
        properties: {
          episodeOfCareId: {
            type: "string",
            description: "The unique ID of the episode of care to update.",
          },
          status: {
            type: "string",
            description: "New status for the episode of care.",
            enum: ["planned", "waitlist", "active", "onhold", "finished", "cancelled", "entered-in-error"],
          },
        },
        required: ["episodeOfCareId"],
      },
    },
  • src/index.ts:981-981 (registration)
    Mapping of tool name to handler function in the toolMapping object used by the MCP server request handler.
    updateEpisodeOfCare,
  • src/index.ts:58-60 (registration)
    Import of the updateEpisodeOfCare handler function from episodeOfCareUtils.
      updateEpisodeOfCare,
      searchEpisodesOfCare,
    } from './tools/episodeOfCareUtils.js';
Behavior2/5

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

With no annotations provided, the description carries the full burden of behavioral disclosure. It states this is an update operation, implying mutation, but doesn't cover permissions, side effects, error handling, or response format. For a mutation tool with zero annotation coverage, this leaves significant gaps in understanding how it behaves.

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 a single, efficient sentence that front-loads the core purpose. It avoids redundancy but could be slightly more informative without losing conciseness, such as hinting at the 'status' field or other updatable aspects.

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 this is a mutation tool with no annotations, no output schema, and incomplete behavioral details, the description is inadequate. It should cover more about the update process, potential impacts, and what to expect in response to be complete for agent use.

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 both parameters. The description adds minimal value by implying 'fields to update' but doesn't elaborate beyond what the schema provides (e.g., details on 'status' enum values). Baseline 3 is appropriate when 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 action ('Updates') and resource ('existing episode of care'), distinguishing it from sibling tools like 'createEpisodeOfCare' and 'getEpisodeOfCareById'. However, it doesn't specify what fields can be updated beyond the implied 'status' from the schema, making it slightly less specific than a perfect score.

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 mentions 'Requires the episode ID and fields to update', which provides basic prerequisites but no guidance on when to use this tool versus alternatives like 'updateCondition' or 'updateEncounter'. It lacks explicit when/when-not scenarios or comparisons to sibling tools.

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