Skip to main content
Glama

swift_package_build

Build Swift packages using swift build with options for target, configuration, architecture, and parse-as-library flag support.

Instructions

Builds a Swift Package with swift build

Input Schema

TableJSON Schema
NameRequiredDescriptionDefault
packagePathYesPath to the Swift package root (Required)
targetNameNoOptional target to build
configurationNoBuild configuration: 'debug' (default) or 'release'
architecturesNoArchitectures to build for (e.g. arm64, x86_64)
parseAsLibraryNoAdd -parse-as-library flag for @main support (default: false)

Implementation Reference

  • The core handler function that executes the 'swift build' command. It validates the packagePath parameter, resolves the path, builds the command arguments based on optional parameters (targetName, configuration, architectures, parseAsLibrary), runs the command via executeCommand, handles success/error responses, and provides user-friendly output.
    }): Promise<ToolResponse> => {
      const pkgValidation = validateRequiredParam('packagePath', params.packagePath);
      if (!pkgValidation.isValid) return pkgValidation.errorResponse!;
    
      const resolvedPath = path.resolve(params.packagePath);
      const args: string[] = ['build', '--package-path', resolvedPath];
    
      if (params.configuration && params.configuration.toLowerCase() === 'release') {
        args.push('-c', 'release');
      }
    
      if (params.targetName) {
        args.push('--target', params.targetName);
      }
    
      if (params.architectures) {
        for (const arch of params.architectures) {
          args.push('--arch', arch);
        }
      }
    
      if (params.parseAsLibrary) {
        args.push('-Xswiftc', '-parse-as-library');
      }
    
      log('info', `Running swift ${args.join(' ')}`);
      try {
        const result = await executeCommand(['swift', ...args], 'Swift Package Build');
        if (!result.success) {
          const errorMessage = result.error || result.output || 'Unknown error';
          return createErrorResponse('Swift package build failed', errorMessage, 'BuildError');
        }
    
        return {
          content: [
            { type: 'text', text: '✅ Swift package build succeeded.' },
            {
              type: 'text',
              text: '💡 Next: Run tests with swift_package_test or execute with swift_package_run',
            },
            { type: 'text', text: result.output },
          ],
        };
      } catch (error) {
        const message = error instanceof Error ? error.message : String(error);
        log('error', `Swift package build failed: ${message}`);
        return createErrorResponse('Failed to execute swift build', message, 'SystemError');
      }
    },
  • Zod input schema defining parameters for the swift_package_build tool, referencing shared Swift Package schemas from common.ts.
      packagePath: z.string().describe('Path to the Swift package root (Required)'),
      targetName: z.string().optional().describe('Optional target to build'),
      configuration: swiftConfigurationSchema,
      architectures: swiftArchitecturesSchema,
      parseAsLibrary: parseAsLibrarySchema,
    },
  • The registration function that registers the 'swift_package_build' tool on the MCP server using registerTool from common.ts, including name, description, schema, and handler.
    export function registerBuildSwiftPackageTool(server: McpServer): void {
      registerTool(
        server,
        'swift_package_build',
        'Builds a Swift Package with swift build',
        {
          packagePath: z.string().describe('Path to the Swift package root (Required)'),
          targetName: z.string().optional().describe('Optional target to build'),
          configuration: swiftConfigurationSchema,
          architectures: swiftArchitecturesSchema,
          parseAsLibrary: parseAsLibrarySchema,
        },
        async (params: {
          packagePath: string;
          targetName?: string;
          configuration?: 'debug' | 'release';
          architectures?: ('arm64' | 'x86_64')[];
          parseAsLibrary?: boolean;
        }): Promise<ToolResponse> => {
          const pkgValidation = validateRequiredParam('packagePath', params.packagePath);
          if (!pkgValidation.isValid) return pkgValidation.errorResponse!;
    
          const resolvedPath = path.resolve(params.packagePath);
          const args: string[] = ['build', '--package-path', resolvedPath];
    
          if (params.configuration && params.configuration.toLowerCase() === 'release') {
            args.push('-c', 'release');
          }
    
          if (params.targetName) {
            args.push('--target', params.targetName);
          }
    
          if (params.architectures) {
            for (const arch of params.architectures) {
              args.push('--arch', arch);
            }
          }
    
          if (params.parseAsLibrary) {
            args.push('-Xswiftc', '-parse-as-library');
          }
    
          log('info', `Running swift ${args.join(' ')}`);
          try {
            const result = await executeCommand(['swift', ...args], 'Swift Package Build');
            if (!result.success) {
              const errorMessage = result.error || result.output || 'Unknown error';
              return createErrorResponse('Swift package build failed', errorMessage, 'BuildError');
            }
    
            return {
              content: [
                { type: 'text', text: '✅ Swift package build succeeded.' },
                {
                  type: 'text',
                  text: '💡 Next: Run tests with swift_package_test or execute with swift_package_run',
                },
                { type: 'text', text: result.output },
              ],
            };
          } catch (error) {
            const message = error instanceof Error ? error.message : String(error);
            log('error', `Swift package build failed: ${message}`);
            return createErrorResponse('Failed to execute swift build', message, 'SystemError');
          }
        },
      );
    }
  • Top-level tool registration entry in the toolRegistrations array. Conditionally registers registerBuildSwiftPackageTool based on the XCODEBUILDMCP_TOOL_SWIFT_PACKAGE_BUILD environment variable.
      register: registerBuildSwiftPackageTool,
      groups: [ToolGroup.SWIFT_PACKAGE_WORKFLOW],
      envVar: 'XCODEBUILDMCP_TOOL_SWIFT_PACKAGE_BUILD',
    },
  • Shared Zod schemas for Swift Package tools: configuration, architectures, and parseAsLibrary options, used by swift_package_build and similar tools.
    export const swiftConfigurationSchema = z
      .enum(['debug', 'release'])
      .optional()
      .describe("Build configuration: 'debug' (default) or 'release'");
    
    export const swiftArchitecturesSchema = z
      .enum(['arm64', 'x86_64'])
      .array()
      .optional()
      .describe('Architectures to build for (e.g. arm64, x86_64)');
    
    export const parseAsLibrarySchema = z
      .boolean()
      .optional()
      .describe('Add -parse-as-library flag for @main support (default: false)');
Behavior2/5

Does the description disclose side effects, auth requirements, rate limits, or destructive behavior?

With no annotations provided, the description carries full burden for behavioral disclosure. 'Builds a Swift Package' implies a potentially time-consuming, resource-intensive operation that may produce artifacts, but the description doesn't mention execution time, output location, error behavior, or what happens when the build fails. For a build tool with zero annotation coverage, this is insufficient behavioral context.

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 states exactly what the tool does without any wasted words. It's appropriately sized for a straightforward build operation and gets directly to the point.

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?

For a build tool with no annotations and no output schema, the description is incomplete. It doesn't explain what the tool produces (executables, libraries, build logs), where outputs go, how to handle build failures, or what success looks like. Given the complexity of build operations and the lack of structured behavioral information, the description should provide more context about the tool's behavior and results.

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 fully documents all 5 parameters. The description adds no parameter information beyond what's in the schema. According to scoring rules, when schema_description_coverage is high (>80%), the baseline is 3 even with no param info in the description.

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 ('Builds') and resource ('a Swift Package with swift build'), making the purpose immediately understandable. It doesn't explicitly differentiate from sibling tools like 'swift_package_run' or 'swift_package_test', but the verb 'Builds' provides reasonable distinction from other Swift package operations.

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 many sibling tools available (including other build tools like 'build_ios_dev_proj' and Swift package operations like 'swift_package_run'), there's no indication of when this specific Swift package build tool is appropriate versus other build or execution options.

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/SampsonKY/XcodeBuildMCP'

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