Skip to main content
Glama
rkirkendall

Medplum MCP Server

by rkirkendall

createCondition

Generate a patient condition or diagnosis by specifying a patient ID, condition code, clinical status, and optional onset or recorded date using the Medplum MCP Server.

Instructions

Creates a new condition or diagnosis for a patient. Requires a patient ID and a condition code.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
clinicalStatusNoThe clinical status of the condition. For example: "active", "inactive", "resolved".
codeYesThe code representing the condition. Must include a coding system, code, and display text.
onsetStringNoEstimated date, state, or age when the condition began (e.g., "about 3 years ago"). Optional.
patientIdYesThe ID of the patient for whom the condition is being created.
recordedDateNoThe date the condition was recorded, in YYYY-MM-DD format. Optional.

Implementation Reference

  • The core handler function that executes the tool logic: validates args, constructs FHIR Condition resource, creates it via Medplum client, handles errors with OperationOutcome.
    export async function createCondition(
      args: CreateConditionArgs,
      client?: MedplumClient,
    ): Promise<Condition | OperationOutcome> {
      const medplumClient = client || medplum;
      await ensureAuthenticated();
      try {
        if (!args.subject || !args.subject.reference) {
          throw new Error('Patient subject reference is required.');
        }
        if (!args.code || !args.code.coding || args.code.coding.length === 0) {
          throw new Error('Condition code with at least one coding is required.');
        }
    
        const conditionResource: Condition = {
          resourceType: 'Condition',
          subject: args.subject,
          code: args.code,
          clinicalStatus: args.clinicalStatus || { coding: [ConditionClinicalStatusCodes.ACTIVE] },
          verificationStatus:
            args.verificationStatus || { coding: [ConditionVerificationStatusCodes.CONFIRMED] },
          category: args.category,
          encounter: args.encounter,
          onsetDateTime: args.onsetDateTime,
          onsetAge: args.onsetAge,
          onsetPeriod: args.onsetPeriod,
          onsetString: args.onsetString,
          recordedDate: args.recordedDate,
          asserter: args.asserter,
        };
    
        // Remove undefined fields to create a clean resource object
        Object.keys(conditionResource).forEach(
          (key) =>
            (conditionResource as any)[key] === undefined && delete (conditionResource as any)[key],
        );
    
        const createdCondition = (await medplumClient.createResource(
          conditionResource,
        )) as Condition;
        console.log('Condition created successfully:', createdCondition.id);
        return createdCondition;
      } catch (error: any) {
        console.error('Error creating Condition:', error);
        const outcome: OperationOutcome = {
          resourceType: 'OperationOutcome',
          issue: [
            {
              severity: 'error',
              code: 'exception',
              diagnostics: `Error creating Condition: ${error.message || 'Unknown error'}`,
            },
          ],
        };
        if (error.outcome) {
          console.error('Server OperationOutcome:', JSON.stringify(error.outcome, null, 2));
          return error.outcome as OperationOutcome;
        }
        return outcome;
      }
    }
  • TypeScript interface defining the input arguments for the createCondition handler.
    export interface CreateConditionArgs {
      subject: Reference<Patient>;
      code: CodeableConcept;
      clinicalStatus?: CodeableConcept;
      verificationStatus?: CodeableConcept;
      category?: CodeableConcept[];
      encounter?: Reference<Encounter>;
      onsetDateTime?: string;
      onsetAge?: Age;
      onsetPeriod?: Period;
      onsetString?: string;
      recordedDate?: string; // ISO 8601 date string
      asserter?: Reference<Patient | Practitioner>;
    }
  • JSON schema definition for the createCondition tool input, used in tool registry.
    name: 'createCondition',
    description:
      'Creates a new condition or diagnosis for a patient. Requires a patient ID and a condition code.',
    input_schema: {
      type: 'object',
      properties: {
        patientId: {
          type: 'string',
          description: 'The ID of the patient for whom the condition is being created.',
        },
        code: {
          type: 'object',
          description:
            'The code representing the condition. Must include a coding system, code, and display text.',
          properties: {
            coding: {
              type: 'array',
              items: {
                type: 'object',
                properties: {
                  system: {
                    type: 'string',
                    description: 'The URI of the coding system (e.g., "http://snomed.info/sct").',
                  },
                  code: { type: 'string', description: 'The code from the system (e.g., "44054006").' },
                  display: {
                    type: 'string',
                    description:
                      'The human-readable display text for the code (e.g., "Type 2 diabetes mellitus").',
                  },
                },
                required: ['system', 'code', 'display'],
              },
            },
            text: { type: 'string', description: 'A human-readable summary of the condition.' },
          },
          required: ['coding', 'text'],
        },
        clinicalStatus: {
          type: 'string',
          description: 'The clinical status of the condition. For example: "active", "inactive", "resolved".',
          enum: ['active', 'recurrence', 'relapse', 'inactive', 'remission', 'resolved'],
        },
        onsetString: {
          type: 'string',
          description:
            'Estimated date, state, or age when the condition began (e.g., "about 3 years ago"). Optional.',
        },
        recordedDate: {
          type: 'string',
          description: 'The date the condition was recorded, in YYYY-MM-DD format. Optional.',
        },
      },
      required: ['patientId', 'code'],
    },
  • src/index.ts:950-988 (registration)
    Tool mapping registry that associates the 'createCondition' string name with the imported handler function for dispatching.
    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:1046-1060 (registration)
    Special dispatching logic in the MCP server request handler that adapts LLM-provided args to the handler's expected CreateConditionArgs format.
     } else if (toolName === 'createCondition') {
       // Special handling for createCondition
       const { patientId, code, clinicalStatus, onsetString, recordedDate } = args;
       const createArgs: any = {
         subject: { reference: `Patient/${patientId}` },
         code,
         onsetString,
         recordedDate,
       };
       if (clinicalStatus) {
         const key = (clinicalStatus as string).toUpperCase() as keyof typeof ConditionClinicalStatusCodes;
         createArgs.clinicalStatus = { coding: [ConditionClinicalStatusCodes[key]] };
       }
       result = await toolFunction(createArgs);
    } else if (toolName === 'searchConditions') {
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 for behavioral disclosure. While 'Creates' implies a write/mutation operation, the description doesn't address important behavioral aspects: whether this requires specific permissions/authorization, what happens on success/failure, whether the creation is reversible, or any rate limits/constraints. For a healthcare data mutation tool with zero annotation coverage, this represents a significant transparency gap.

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 appropriately concise with two sentences that efficiently state the purpose and prerequisites. There's no unnecessary verbiage, and the information is front-loaded. However, it could be slightly more structured by separating purpose from requirements more clearly, and the second sentence could be integrated more smoothly.

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 this is a mutation tool (creating patient conditions) with no annotations and no output schema, the description provides minimal but adequate context. It identifies the tool's purpose and basic requirements, but doesn't address the complexity implied by 5 parameters (including nested objects) or provide guidance on the clinical workflow. For a healthcare data creation tool, more context about validation, error handling, or integration with sibling tools would be beneficial.

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 provides comprehensive parameter documentation. The description mentions 'patient ID and a condition code' which aligns with the two required parameters but doesn't add meaningful semantic context beyond what's already in the schema descriptions. The baseline score of 3 is appropriate when the schema does the heavy lifting, though the description could have explained the clinical significance of parameters like 'clinicalStatus' or 'onsetString'.

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 ('Creates a new condition or diagnosis') and the target resource ('for a patient'), which provides specific verb+resource information. However, it doesn't explicitly differentiate this tool from sibling tools like 'createObservation' or 'createMedication' that also create clinical resources, missing the opportunity to clarify this is specifically for conditions/diagnoses rather than other FHIR resource types.

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 a patient ID and a condition code' which indicates prerequisites but doesn't provide guidance on when to use this tool versus alternatives. With sibling tools like 'updateCondition' and 'searchConditions' available, there's no indication of when to create versus update or when to use this versus general search tools. The description lacks explicit when/when-not guidance or alternative recommendations.

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