Skip to main content
Glama
rkirkendall

Medplum MCP Server

by rkirkendall

generalFhirSearch

Execute FHIR searches across any resource type with custom parameters using the Medplum MCP Server. Retrieve healthcare data efficiently by specifying resource types and query criteria.

Instructions

Performs a generic FHIR search operation on any resource type with custom query parameters.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
queryParamsYesA record of query parameters, where keys are FHIR search parameters and values are their corresponding values.
resourceTypeYesThe FHIR resource type to search for (e.g., 'Patient', 'Observation').

Implementation Reference

  • The core handler function that executes the general FHIR search logic using the Medplum client. It constructs the query string from provided parameters and performs the search, handling errors with OperationOutcome.
    export async function generalFhirSearch(
      args: GeneralFhirSearchArgs,
      client?: MedplumClient,
    ): Promise<Bundle<Resource> | OperationOutcome> {
      const medplumClient = client || medplum;
      await ensureAuthenticated();
    
      try {
        if (!args.resourceType) {
          return {
            resourceType: 'OperationOutcome',
            issue: [
              {
                severity: 'error',
                code: 'invalid',
                diagnostics: 'Resource type is required for general FHIR search.',
              },
            ],
          };
        }
    
        if (!args.queryParams || Object.keys(args.queryParams).length === 0) {
          return {
            resourceType: 'OperationOutcome',
            issue: [
              {
                severity: 'error',
                code: 'invalid',
                diagnostics: 'At least one query parameter is required for general FHIR search.',
              },
            ],
          };
        }
    
        // Construct the query string from queryParams
        const queryString = Object.entries(args.queryParams)
          .map(([key, value]) => {
            if (Array.isArray(value)) {
              // For _id, comma-separate: field=_id=v1,v2,v3
              if (key === '_id') {
                return `${encodeURIComponent(key)}=${value.map(v => String(v)).join(',')}`;
              }
              // For other array values, create multiple parameters: key=v1&key=v2
              return value.map(v => `${encodeURIComponent(key)}=${encodeURIComponent(String(v))}`).join('&');
            }
            return `${encodeURIComponent(key)}=${encodeURIComponent(String(value))}`;
          })
          .join('&');
    
        console.log(`Performing general FHIR search for type "${args.resourceType}" with query: ${queryString}`);
    
        // Medplum SDK's search method can take ResourceType or a string for the resource type.
        // The result is a Bundle of the specified Resource type.
        const result = (await medplumClient.search(args.resourceType as ResourceType, queryString)) as Bundle<Resource>; 
        
        console.log(`General FHIR search found ${result.entry?.length || 0} resources.`);
        return result;
    
      } catch (error: any) {
        console.error(`Error during general FHIR search for type "${args.resourceType}":`, error);
        if (error.outcome) { // Prefer the outcome from the error if available
          return error.outcome as OperationOutcome;
        }
        // Fallback to a generic OperationOutcome
        return {
          resourceType: 'OperationOutcome',
          issue: [
            {
              severity: 'error',
              code: 'exception',
              diagnostics: `Error during general FHIR search: ${error.message || 'Unknown error'}`,
            },
          ],
        };
      }
    } 
  • JSON Schema definition for the generalFhirSearch tool input, defining resourceType and queryParams with detailed descriptions and examples.
      name: 'generalFhirSearch',
      description: 'Performs a generic search for any FHIR resource type using specified query parameters. Useful when the exact resource type is known and specific search criteria need to be applied, or for resource types not covered by other specialized tools.',
      input_schema: {
        type: 'object',
        properties: {
          resourceType: {
            type: 'string',
            description: "The FHIR resource type to search for (e.g., 'Patient', 'Observation', 'MedicationRequest'). This must be a valid FHIR resource type name.",
            // Potentially add an enum of common ResourceTypes if helpful for LLM, but can be very long.
            // Example enum (partial): enum: ['Patient', 'Practitioner', 'Organization', 'Encounter', 'Observation', 'MedicationRequest', 'Condition', 'Procedure', 'DiagnosticReport']
          },
          queryParams: {
            type: 'object',
            description: "An object where keys are FHIR search parameters (e.g., 'name', 'date', '_id', 'patient') and values are the corresponding search values. For parameters that can appear multiple times (like 'date' for a range), provide an array of strings as the value (e.g., { date: ['ge2023-01-01', 'le2023-01-31'] }). For token parameters (codeableConcepts), provide the value as 'system|code' or just 'code'. For reference parameters, use 'ResourceType/id' or just 'id'.",
            additionalProperties: {
              oneOf: [
                { type: 'string' },
                { type: 'number' },
                { type: 'boolean' },
                { type: 'array', items: { type: 'string' } }
              ]
            },
            example: {
              _id: "12345",
              status: "active",
              "patient.name": "John Doe",
              date: ["ge2024-01-01", "le2024-01-31"]
            }
          }
        },
        required: ['resourceType', 'queryParams']
      }
    },
  • src/index.ts:922-946 (registration)
    MCP tool registration in the mcpTools array, including schema and description for the generalFhirSearch tool.
      name: "generalFhirSearch",
      description: "Performs a generic FHIR search operation on any resource type with custom query parameters.",
      inputSchema: {
        type: "object",
        properties: {
          resourceType: {
            type: "string",
            description: "The FHIR resource type to search for (e.g., 'Patient', 'Observation').",
          },
          queryParams: {
            type: "object",
            description: "A record of query parameters, where keys are FHIR search parameters and values are their corresponding values.",
            additionalProperties: {
              oneOf: [
                { type: "string" },
                { type: "number" },
                { type: "boolean" },
                { type: "array", items: { type: "string" } }
              ]
            },
          },
        },
        required: ["resourceType", "queryParams"],
      },
    },
  • src/index.ts:70-71 (registration)
    Import statement bringing the generalFhirSearch handler function into the main index file.
      generalFhirSearch,
    } from './tools/generalFhirSearchUtils.js';
  • src/index.ts:987-987 (registration)
    Mapping of the tool name to its handler function in the toolMapping object used for execution.
    generalFhirSearch,
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 'performs a generic FHIR search operation' but doesn't disclose behavioral traits like whether it's read-only (implied by 'search'), authentication needs, rate limits, pagination, error handling, or output format. For a search tool with no 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 a single, efficient sentence that front-loads the core purpose without unnecessary words. Every part earns its place by defining the operation, scope, and key parameters concisely.

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 generic FHIR search tool with no annotations, no output schema, and many sibling alternatives, the description is incomplete. It lacks details on behavior, usage context, and output, leaving the agent under-informed for effective tool selection and invocation.

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%, with clear descriptions for both parameters (resourceType and queryParams). The description adds minimal value beyond the schema, mentioning 'custom query parameters' which aligns with the schema's 'queryParams' description. 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 performs a 'generic FHIR search operation on any resource type with custom query parameters,' which specifies the verb ('performs search'), resource ('any FHIR resource type'), and scope ('generic'). It distinguishes itself from sibling tools like searchPatients or searchObservations by emphasizing its generic nature, though it doesn't explicitly contrast with them in the text.

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 versus the many specific search siblings (e.g., searchPatients, searchObservations). It mentions 'any resource type' but doesn't clarify if this is preferred for ad-hoc queries or when specific tools are unavailable, leaving the agent to guess based on context.

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