Skip to main content
Glama
rkirkendall

Medplum MCP Server

by rkirkendall

createObservation

Generate and store new medical observations, such as lab results or vital signs, by providing patient ID, observation code, and required details using the Medplum MCP Server.

Instructions

Creates a new observation (lab result, vital sign, etc.). Requires patient ID and code.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
codeYesThe code representing what was observed (LOINC, SNOMED CT, etc.).
encounterIdNoThe encounter this observation is associated with. Optional.
patientIdYesThe ID of the patient this observation is for.
statusYesThe status of the observation.
valueQuantityNoNumeric value of the observation. Optional.
valueStringNoString value of the observation. Optional.

Implementation Reference

  • The main handler function that implements the createObservation tool logic. It constructs an Observation FHIR resource from the input arguments, performs validations, handles ID-to-reference conversions, and calls medplum.createResource to persist it.
    export async function createObservation(args: CreateObservationArgs): Promise<Observation> {
      await ensureAuthenticated();
    
      // Handle subjectId conversion for convenience
      let subject = args.subject;
      if (args.subjectId && !subject) {
        subject = { reference: `Patient/${args.subjectId}` };
      }
    
      // Handle encounterId conversion for convenience
      let encounter = args.encounter;
      if (args.encounterId && !encounter) {
        encounter = { reference: `Encounter/${args.encounterId}` };
      }
    
      // Handle performerIds conversion for convenience
      let performer = args.performer;
      if (args.performerIds && !performer) {
        performer = args.performerIds.map(id => ({ reference: `Practitioner/${id}` }));
      }
    
      if (!subject?.reference) {
        throw new Error('Patient reference is required to create an observation.');
      }
      if (!args.code || !args.code.coding || args.code.coding.length === 0) {
        throw new Error('Observation code with at least one coding is required.');
      }
      if (!args.status) {
        throw new Error('Observation status is required.');
      }
      if (
        args.valueQuantity === undefined && args.valueCodeableConcept === undefined && args.valueString === undefined && args.valueBoolean === undefined &&
        args.valueInteger === undefined && args.valueRange === undefined && args.valueRatio === undefined && args.valueSampledData === undefined &&
        args.valueTime === undefined && args.valueDateTime === undefined && args.valuePeriod === undefined
      ) {
        throw new Error('At least one value field must be provided (valueQuantity, valueCodeableConcept, valueString, valueBoolean, valueInteger, valueRange, valueRatio, valueSampledData, valueTime, valueDateTime, or valuePeriod).');
      }
    
      const observationResource: Observation = {
        resourceType: 'Observation',
        status: args.status,
        code: args.code,
        subject: subject,
        encounter: encounter,
        effectiveDateTime: args.effectiveDateTime,
        effectivePeriod: args.effectivePeriod,
        issued: args.issued || new Date().toISOString(),
        performer: performer,
        valueQuantity: args.valueQuantity,
        valueCodeableConcept: args.valueCodeableConcept,
        valueString: args.valueString,
        valueBoolean: args.valueBoolean,
        valueInteger: args.valueInteger,
        valueRange: args.valueRange,
        valueRatio: args.valueRatio,
        valueSampledData: args.valueSampledData,
        valueTime: args.valueTime,
        valueDateTime: args.valueDateTime,
        valuePeriod: args.valuePeriod,
        bodySite: args.bodySite,
        method: args.method,
        referenceRange: args.referenceRange,
        note: args.note ? [{ text: args.note }] : undefined,
        interpretation: args.interpretation,
        identifier: args.identifier ? [{ system: args.identifier.system, value: args.identifier.value }] : undefined,
      };
    
      if (args.component) {
        observationResource.component = args.component;
      }
    
      return medplum.createResource<Observation>(observationResource);
    }
  • TypeScript interface defining the input arguments for the createObservation function, providing type safety and documentation for the expected parameters.
    export interface CreateObservationArgs {
      status: Observation['status'];
      code: CodeableConcept;
      subject?: Reference<Patient>; // Made optional since tests use subjectId
      subjectId?: string; // For convenience in tests - will be converted to subject reference
      encounter?: Reference<Encounter>;
      encounterId?: string; // For convenience in tests - will be converted to encounter reference
      effectiveDateTime?: string;
      effectivePeriod?: Period;
      issued?: string;
      performer?: Reference<Practitioner>[];
      performerIds?: string[]; // For convenience in tests - will be converted to performer references
      valueQuantity?: Quantity;
      valueString?: string;
      valueBoolean?: boolean;
      valueCodeableConcept?: CodeableConcept;
      valueInteger?: number;
      valueRange?: Range;
      valueRatio?: Ratio;
      valueSampledData?: SampledData;
      valueTime?: string;
      valueDateTime?: string;
      valuePeriod?: Period;
      bodySite?: CodeableConcept;
      method?: CodeableConcept;
      component?: any[];
      interpretation?: CodeableConcept[];
      note?: string;
      referenceRange?: any[];
      identifier?: { system?: string; value: string };
    }
  • src/index.ts:459-492 (registration)
    MCP tool registration including the name, description, and input schema for the createObservation tool, used by the ListToolsRequest handler.
      name: "createObservation",
      description: "Creates a new observation (lab result, vital sign, etc.). Requires patient ID and code.",
      inputSchema: {
        type: "object",
        properties: {
          patientId: {
            type: "string",
            description: "The ID of the patient this observation is for.",
          },
          code: {
            type: "string",
            description: "The code representing what was observed (LOINC, SNOMED CT, etc.).",
          },
          valueQuantity: {
            type: "number",
            description: "Numeric value of the observation. Optional.",
          },
          valueString: {
            type: "string",
            description: "String value of the observation. Optional.",
          },
          status: {
            type: "string",
            description: "The status of the observation.",
            enum: ["registered", "preliminary", "final", "amended", "corrected", "cancelled"],
          },
          encounterId: {
            type: "string",
            description: "The encounter this observation is associated with. Optional.",
          },
        },
        required: ["patientId", "code", "status"],
      },
    },
  • src/index.ts:968-968 (registration)
    Mapping of the createObservation function to the tool name in the toolMapping object, used by the CallToolRequest handler to execute the tool.
    createObservation,
  • src/index.ts:39-43 (registration)
    Import statement bringing the createObservation handler into the main index file for registration.
      createObservation,
      getObservationById,
      updateObservation,
      searchObservations,
    } from './tools/observationUtils.js';
Behavior2/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 that creation requires specific inputs ('patient ID and code'), but fails to describe behavioral traits such as permissions needed, whether the operation is idempotent, error handling, or what the response looks like. For a mutation 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.

Conciseness5/5

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

The description is appropriately sized with two concise sentences: one stating the purpose with examples, and another specifying requirements. It's front-loaded with the core action and wastes no words, making it easy to scan and understand quickly.

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 annotations and no output schema, the description provides basic purpose and requirements but lacks details on behavioral aspects, error cases, or return values. For a creation tool in a healthcare context with multiple parameters, it's minimally adequate but leaves gaps in understanding full usage and outcomes.

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 already documents all 6 parameters thoroughly. The description adds minimal value by mentioning 'patient ID and code' as required, but doesn't provide additional context beyond what's in the schema. 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 verb ('creates') and resource ('new observation') with helpful examples ('lab result, vital sign, etc.'). It distinguishes from sibling tools like 'updateObservation' by specifying creation rather than modification, though it doesn't explicitly contrast with other creation tools like 'createPatient' or 'createEncounter' beyond the resource type.

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 context through 'Requires patient ID and code,' suggesting prerequisites, but doesn't explicitly state when to use this tool versus alternatives like 'updateObservation' or 'searchObservations.' It hints at mandatory parameters but lacks guidance on scenarios or exclusions compared 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