Skip to main content
Glama
rkirkendall

Medplum MCP Server

by rkirkendall

searchObservations

Search for patient observations by criteria like ID, code, or status using the Medplum MCP Server, enabling efficient healthcare data management.

Instructions

Searches for observations based on criteria like patient ID or code.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
codeNoThe observation code to filter by. Optional.
encounterIdNoThe encounter ID to search observations for. Optional.
patientIdNoThe patient ID to search observations for. Optional.
statusNoThe observation status to filter by. Optional.

Implementation Reference

  • The core handler function that implements the searchObservations tool logic. It authenticates, builds FHIR search parameters from input args, and performs the search using medplum.searchResources.
    export async function searchObservations(args: ObservationSearchArgs): Promise<Observation[]> {
      await ensureAuthenticated();
      const searchCriteria: string[] = [];
    
      if (Object.keys(args).length === 0) {
        console.warn('Observation search called with no specific criteria. This might return a large number of results or be inefficient.');
      }
    
      if (args.patientId) {
        searchCriteria.push(`subject=Patient/${args.patientId}`);
      } else if (args.subject) { 
         searchCriteria.push(`subject=${args.subject}`);
      }
    
      if (args.code) {
        if (args.codeSystem) {
          searchCriteria.push(`code=${args.codeSystem}|${args.code}`);
        } else {
          searchCriteria.push(`code=${args.code}`);
        }
      }
      if (args.encounterId) {
        searchCriteria.push(`encounter=Encounter/${args.encounterId}`);
      }
      if (args.date) {
        // If no comparator is provided, default to 'eq' for exact date match
        const dateValue = args.date.match(/^(eq|ne|gt|lt|ge|le)/) ? args.date : `eq${args.date}`;
        searchCriteria.push(`date=${dateValue}`); 
      }
      if (args.status) {
        searchCriteria.push(`status=${args.status}`);
      }
       if (args.performer) {
        searchCriteria.push(`performer=${args.performer}`);
      }
      if (args.identifier) {
        searchCriteria.push(`identifier=${args.identifier}`);
      }
      if (args._lastUpdated) {
        searchCriteria.push(`_lastUpdated=${args._lastUpdated}`);
      }
    
      if (searchCriteria.length === 0 && Object.keys(args).length > 0) {
        console.warn('Observation search arguments provided but did not map to any known search parameters:', args);
        return [];
      }
      
      if (searchCriteria.length > 0 || Object.keys(args).length === 0) {
          const queryString = searchCriteria.join('&');
          // console.log(`Searching observations with query: ${queryString}`); // Optional: for debugging
          return medplum.searchResources('Observation', queryString);
      } else {
          return [];
      }
    } 
  • TypeScript interface defining the input parameters accepted by the searchObservations handler.
    export interface ObservationSearchArgs {
      patientId?: string;
      code?: string; // Search by LOINC or other code system code
      codeSystem?: string; // Specify the system for the code
      encounterId?: string;
      date?: string; // Search by effectiveDateTime or effectivePeriod
      status?: Observation['status'];
      subject?: string; // FHIR style search param: Patient/XYZ
      performer?: string; // FHIR style search param: Practitioner/XYZ
      identifier?: string; // Search by identifier value (e.g. value or system|value)
      _lastUpdated?: string; // Search by last updated date
    }
  • MCP protocol input schema definition for the searchObservations tool, used for validation and tool listing.
    {
      name: "searchObservations",
      description: "Searches for observations based on criteria like patient ID or code.",
      inputSchema: {
        type: "object",
        properties: {
          patientId: {
            type: "string",
            description: "The patient ID to search observations for. Optional.",
          },
          code: {
            type: "string",
            description: "The observation code to filter by. Optional.",
          },
          status: {
            type: "string",
            description: "The observation status to filter by. Optional.",
            enum: ["registered", "preliminary", "final", "amended", "corrected", "cancelled"],
          },
          encounterId: {
            type: "string",
            description: "The encounter ID to search observations for. Optional.",
          },
        },
        required: [],
      },
    },
  • src/index.ts:950-988 (registration)
    The toolMapping object registers 'searchObservations' by mapping the tool name to its imported handler function, used by the MCP server request handler to dispatch calls.
    const toolMapping: Record<string, (...args: any[]) => Promise<any>> = {
      createPatient,
      getPatientById, 
      updatePatient,
      searchPatients,
      searchPractitionersByName,
      createPractitioner,
      getPractitionerById,
      updatePractitioner,
      searchPractitioners,
      createOrganization,
      getOrganizationById,
      updateOrganization,
      searchOrganizations,
      createEncounter,
      getEncounterById,
      updateEncounter,
      searchEncounters,
      createObservation,
      getObservationById,
      updateObservation,
      searchObservations,
      createMedicationRequest,
      getMedicationRequestById,
      updateMedicationRequest,
      searchMedicationRequests,
      createMedication,
      getMedicationById,
      searchMedications,
      createEpisodeOfCare,
      getEpisodeOfCareById,
      updateEpisodeOfCare,
      searchEpisodesOfCare,
      createCondition,
      getConditionById,
      updateCondition,
      searchConditions,
      generalFhirSearch,
    };
  • src/index.ts:39-44 (registration)
    Import statement that brings the searchObservations handler function into the main index file for registration.
      createObservation,
      getObservationById,
      updateObservation,
      searchObservations,
    } from './tools/observationUtils.js';
    import {
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. It states it's a search operation but doesn't disclose behavioral traits like pagination, rate limits, authentication needs, or what happens with multiple criteria. The description is minimal and lacks essential context for a search tool.

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 with no wasted words. It's front-loaded with the core purpose. However, it could be more structured by explicitly listing key use cases or constraints.

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 complexity of a search tool with 4 parameters, no annotations, and no output schema, the description is incomplete. It lacks details on behavior, output format, error handling, and usage context, leaving significant gaps for an AI agent.

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. The description adds minimal value by mentioning 'patient ID or code' as examples, but doesn't provide additional semantics beyond what's in the schema. Baseline 3 is appropriate as the schema handles parameter documentation.

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 ('searches for') and resource ('observations'), and specifies criteria like patient ID or code. However, it doesn't explicitly distinguish this tool from sibling search tools (e.g., searchConditions, searchEncounters) beyond mentioning 'observations'.

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 is provided on when to use this tool versus alternatives. The description mentions criteria but doesn't specify scenarios, prerequisites, or exclusions compared to other search tools or getObservationById.

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