Skip to main content
Glama
Derrbal

TestRail MCP Server

by Derrbal

Add Attachment to TestRail Case

add_attachment_to_case

Upload file attachments to TestRail test cases to provide supporting documentation, evidence, or reference materials for comprehensive test management.

Instructions

Upload a file attachment to a TestRail test case.

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
case_idYesTestRail case ID
file_pathYesPath to the file to upload as attachment

Implementation Reference

  • MCP tool handler function that executes the add_attachment_to_case logic: logs input, calls service function, returns JSON response or formatted error.
    async ({ case_id, file_path }) => {
      logger.debug(`Add attachment tool called with case_id: ${case_id}, file_path: ${file_path}`);
      try {
        const result = await addAttachmentToCase(case_id, file_path);
        logger.debug(`Add attachment tool completed successfully for case_id: ${case_id}, attachment_id: ${result.attachment_id}`);
        return {
          content: [
            {
              type: 'text',
              text: JSON.stringify(result, null, 2),
            },
          ],
        };
      } catch (err) {
        logger.error({ err }, `Add attachment tool failed for case_id: ${case_id}, file_path: ${file_path}`);
        const e = err as { type?: string; status?: number; message?: string };
        let message = 'Unexpected error';
        if (e?.type === 'auth') message = 'Authentication failed: check TESTRAIL_USER/API_KEY';
        else if (e?.type === 'not_found') message = `Case ${case_id} not found`;
        else if (e?.type === 'rate_limited') message = 'Rate limited by TestRail; try again later';
        else if (e?.type === 'server') message = 'TestRail server error';
        else if (e?.type === 'network') message = 'Network error contacting TestRail';
        else if (e?.message) message = e.message;
    
        return {
          content: [
            { type: 'text', text: message },
          ],
          isError: true,
        };
      }
    },
  • Zod input schema defining parameters: case_id (positive integer), file_path (non-empty string). Title and description for the tool.
    {
      title: 'Add Attachment to TestRail Case',
      description: 'Upload a file attachment to a TestRail test case.',
      inputSchema: {
        case_id: z.number().int().positive().describe('TestRail case ID'),
        file_path: z.string().min(1).describe('Path to the file to upload as attachment'),
      },
  • src/server.ts:469-511 (registration)
    Registers the 'add_attachment_to_case' tool with MCP server using schema and handler.
    server.registerTool(
      'add_attachment_to_case',
      {
        title: 'Add Attachment to TestRail Case',
        description: 'Upload a file attachment to a TestRail test case.',
        inputSchema: {
          case_id: z.number().int().positive().describe('TestRail case ID'),
          file_path: z.string().min(1).describe('Path to the file to upload as attachment'),
        },
      },
      async ({ case_id, file_path }) => {
        logger.debug(`Add attachment tool called with case_id: ${case_id}, file_path: ${file_path}`);
        try {
          const result = await addAttachmentToCase(case_id, file_path);
          logger.debug(`Add attachment tool completed successfully for case_id: ${case_id}, attachment_id: ${result.attachment_id}`);
          return {
            content: [
              {
                type: 'text',
                text: JSON.stringify(result, null, 2),
              },
            ],
          };
        } catch (err) {
          logger.error({ err }, `Add attachment tool failed for case_id: ${case_id}, file_path: ${file_path}`);
          const e = err as { type?: string; status?: number; message?: string };
          let message = 'Unexpected error';
          if (e?.type === 'auth') message = 'Authentication failed: check TESTRAIL_USER/API_KEY';
          else if (e?.type === 'not_found') message = `Case ${case_id} not found`;
          else if (e?.type === 'rate_limited') message = 'Rate limited by TestRail; try again later';
          else if (e?.type === 'server') message = 'TestRail server error';
          else if (e?.type === 'network') message = 'Network error contacting TestRail';
          else if (e?.message) message = e.message;
    
          return {
            content: [
              { type: 'text', text: message },
            ],
            isError: true,
          };
        }
      },
    );
  • Service layer wrapper that calls TestRail client and normalizes response to {attachment_id}.
    export async function addAttachmentToCase(caseId: number, filePath: string): Promise<AttachmentResponse> {
      const response: TestRailAttachmentResponse = await testRailClient.addAttachmentToCase(caseId, filePath);
      
      return {
        attachment_id: response.attachment_id,
      };
    }
  • TestRailClient method that performs multipart file upload to TestRail API endpoint /add_attachment_to_case/{caseId} using FormData and axios.
    async addAttachmentToCase(caseId: number, filePath: string): Promise<TestRailAttachmentResponse> {
      try {
        // Import FormData dynamically to avoid issues in Node.js environment
        const FormData = (await import('form-data')).default;
        const fs = await import('fs');
        
        const formData = new FormData();
        const fileStream = fs.createReadStream(filePath);
        const fileName = filePath.split(/[/\\]/).pop() || 'attachment';
        
        formData.append('attachment', fileStream, fileName);
        
        // Create a new axios instance for multipart upload
        const uploadClient = axios.create({
          baseURL: `${config.TESTRAIL_URL}/index.php?/api/v2`,
          timeout: config.TESTRAIL_TIMEOUT_MS,
          auth: {
            username: config.TESTRAIL_USERNAME,
            password: config.TESTRAIL_API_KEY,
          },
          headers: {
            ...formData.getHeaders(),
          },
          validateStatus: () => true,
        });
    
        const res = await uploadClient.post(`/add_attachment_to_case/${caseId}`, formData);
        
        if (res.status >= 200 && res.status < 300) {
          return res.data as TestRailAttachmentResponse;
        }
        throw Object.assign(new Error(`HTTP ${res.status}`), { response: res });
      } catch (err) {
        const normalized = this.normalizeError(err);
        const safeDetails = this.getSafeErrorDetails(err);
        logger.error({ err: normalized, details: safeDetails, caseId, filePath }, 'TestRail addAttachmentToCase failed');
        throw normalized;
      }
    }
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 of behavioral disclosure. While 'Upload a file attachment' implies a write/mutation operation, it lacks critical details: required permissions (e.g., edit access to the case), file size/type limits, whether the attachment is public or private, or how failures are handled. This is inadequate for a mutation tool with zero annotation coverage.

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 action and target. There's no wasted wording or redundancy, making it easy to parse quickly while conveying the essential purpose.

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 file upload operation (mutation with potential side effects), no annotations, and no output schema, the description is incomplete. It doesn't address behavioral aspects like error handling, response format, or constraints, leaving significant gaps for the agent to navigate blindly.

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 parameter descriptions in the schema itself (e.g., 'TestRail case ID', 'Path to the file to upload as attachment'). The description adds no additional semantic context beyond what's already in the schema, such as example file paths or case ID formats. This meets the baseline for high schema coverage but doesn't enhance understanding.

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 ('Upload a file attachment') and target resource ('to a TestRail test case'), making the purpose immediately understandable. However, it doesn't differentiate from potential sibling tools like 'add_case' or 'add_result' that also involve adding content to TestRail, leaving room for confusion about when to choose this specific tool.

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 alternatives. With sibling tools like 'add_case' (for creating cases) and 'add_result' (for adding test results), there's no indication of whether this is for supplementary files, required documentation, or specific contexts like bug reports. The agent must infer usage from the name alone.

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

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/Derrbal/testrail-mcp'

If you have feedback or need assistance with the MCP directory API, please join our Discord server