AI Knowledge Hub
Menu
Back to the libraryGuide / Systems & agents

The Muscles of the Machine: Designing the Marketing Agent's Tool Layer

How to build and operate marketing-agent tools through MCP, CLI, or both, with explicit contracts, validation, permissions, evaluation, and deployment boundaries.

A marketing agent becomes operational when its requests reach real systems. It can retrieve campaign data, calculate a comparison, prepare a report, publish a message, or change a bid. At that boundary, an interpretation becomes a query or an effect. The surrounding software must establish what is allowed, what happened, and what the returned result actually means.

MCP and command-line tools offer different ways to make those operations available. Choosing between them matters, but it is only one part of the design. Neither interface supplies client isolation, correct metric definitions, reliable retries, or evidence that the agent completed its task. Those properties have to survive the entire path from the request to the provider and back.

The Agent Architect’s Playbook covers the complete operating lifecycle. The Anatomy of a Marketing Agent explains how its parts interact. This guide focuses on their execution boundary: designing tools, exposing them through MCP or CLI, controlling their effects, and testing the deployed system that uses them.

Start with the operation, then choose its interface

A tool is an operation the runtime can carry out on the model’s request. Reading campaign metrics, checking a landing page, preparing an audience preview, and applying an approved bid change are different operations with different requirements.

The model chooses among the capabilities it is offered and supplies proposed inputs. The runtime and backend validate and authorize those inputs, execute the permitted operation, and return evidence or an explicit failure. A skill can guide the investigation, but its instructions do not grant access or execute the call themselves.

A useful tool contract includes more than its name and parameters:

Contract elementWhat a marketing implementation needs to establish
Purpose and descriptionWhich task the operation serves and when the agent should use it
Input requirementsSupported accounts, dates, dimensions, metrics, units, and limits
Trusted identityWhich authenticated user, client, and workflow the request belongs to
AuthorityWho may invoke the operation against the resolved target, under which policy
Output meaningSource, account scope, metric definitions, freshness, coverage, and result status
Effects and repetitionWhat can change, and what a repeated or interrupted call might do
Failure behaviorHow denial, ambiguity, unsupported operations, partial results, and provider failure are represented
Operating limitsTimeouts, query cost, pagination bounds, rate limits, cancellation, and version compatibility

A tool is not necessarily deterministic in the sense of returning the same value for the same inputs. Live metrics change, providers fail, and generative operations vary. Predictability comes from explicit semantics: a caller understands the conditions, possible results, and effects, including uncertainty.

For example, “retrieve campaign metrics” should define whether its dates are inclusive, which time zone applies, whether conversions can arrive late, and how incomplete pagination is reported. “Adjust a bid” needs an exact target and approved change, plus rules for stale state, concurrent edits, and repeated requests. These decisions precede MCP or CLI packaging.

Follow a read through the complete tool boundary

For the series’ weekly-review brief, this call retrieves the paid-search portion for 12–18 October 2026. A second call retrieves the comparison week, 5–11 October, under the same definitions. The model proposes account and reporting parameters; the application supplies authenticated client and user context. A model-provided client_id cannot substitute for that context.

The system resolves the account inside the permitted client scope, checks access to the requested data, validates the reporting parameters, and dispatches the provider request. It records whether all required data arrived and whether the provider changed or rejected any requested fields. The result reaches the agent with its limitations intact.

A proposed tool request passes through scope resolution, authorization, bounded execution, result validation, and an evidence-linked response. Observation and evaluation support the full loop.
The model proposes a call. Software checks authority and executes it; validated evidence supports the next reasoning step.

The agent can then request another breakdown or explain what it found. The harness tracks pending calls, failures, remaining budget, and whether the job is still active. If one platform is unavailable, a partial comparison remains partial. A transport success is not proof of complete reporting coverage.

The same path applies when a child agent requests data. Delegation changes who reasons about the task, but should not widen the client’s permissions or erase the parent’s budget. Carry the job and worker identity into the tool record so operators can reconstruct the combined workflow.

MCP: a common connection to external capabilities

The Model Context Protocol standardizes communication between AI applications and external capability providers. The host is the application managing the agent. Its MCP client communicates with an MCP server that exposes operations and context. The server still needs an implementation behind those operations. See the MCP architecture documentation.

A shared interface can reduce repeated connector work. With three hosts and eight sources, bespoke host-to-source integrations could produce twenty-four combinations. A common protocol allows more reuse on each side. This is an architectural motivation, not a guarantee that eleven interchangeable components eliminate every integration cost. Authentication, supported features, schema versions, deployment, and provider semantics still need to match.

Two MCP clients in an agent host connect to local or remote MCP servers, which expose capabilities backed by external providers. Host and server controls preserve identity, permissions and evidence.
MCP connects the host to capability providers. The connection does not replace application policy or provider authorization.

Tools, resources, prompts, and skills

MCP describes server features including tools for operations, resources for readable context, and prompts for reusable interaction templates. A tool might retrieve campaign metrics; a resource might expose approved metric definitions; a prompt might supply a template for asking about those metrics. These features have distinct roles in the protocol architecture.

An Agent Skill is a separate instruction package loaded by a supporting runtime. It may guide the use of MCP tools and resources or of other capabilities. A server prompt and a SKILL.md package are not interchangeable simply because both contain instructions.

Tool definitions describe names, inputs, and other metadata. The MCP tool specification defines the protocol representation. Those definitions help the host and model form calls, but the handler still needs to check actual ownership, permission, input bounds, and provider results. Declaring a tool read-only does not prove that its implementation cannot write.

Local and remote connections have different operating needs

A local server can run as a process connected through standard input and output, commonly called stdio. These are streams used by programs to exchange messages; they are not necessarily an interactive terminal. Keep diagnostics separate from the protocol stream so a log line does not corrupt a message.

A remote server can use Streamable HTTP. It needs service deployment, authentication, caller isolation, request limits, and operational monitoring. A local server needs process isolation, controlled filesystem and credential access, and careful handling of subprocesses. Local does not mean trusted, and remote does not mean governed.

Use the supported transport and SDK version for the host. Avoid assuming a setup fragment works across products or protocol revisions. The durable architecture is the capability contract and its controls; installation details belong to the versioned implementation documentation.

CLI: operations expressed as commands

A command-line interface accepts command arguments, performs work, and produces output and a process exit status. It is attractive when an agent already has controlled code execution or a reliable command-line program exists for the task.

The Unix tradition of small programs and streams offers useful design principles: give an operation a clear purpose, make its output usable by another program, and allow composition. For agent workflows, structured data is often more dependable than text designed only for a human screen.

The series uses marketing report as its illustrative internal retrieval command. It is an interface to implement, not a public package to install. This invocation requests one provider account and channel; the review skill combines the approved source results:

marketing report \
  --account ACCOUNT_REF \
  --channel paid_search \
  --since 2026-10-12 \
  --until 2026-10-18 \
  --json

The command parser supplies explicit arguments to the same authorized reporting service an MCP adapter could call. It should reject unsupported dates, fields, or scope rather than quietly substituting a default advertiser. Credentials and authenticated client context come from the trusted execution setup, not arbitrary flags supplied by the model.

Compose results without hiding failures

A CLI can write a larger result to a controlled file and use a tool such as jq, a JSON processor, to select the relevant fields before they enter model context. That is useful for a reporting workflow, provided the selection preserves the information needed to interpret the data.

In Bash, an illustrative pipeline might be:

set -o pipefail
marketing report \
  --account ACCOUNT_REF \
  --channel paid_search \
  --since 2026-10-12 \
  --until 2026-10-18 \
  --json \
  | jq '{status, scope, coverage, metrics}'

pipefail helps surface a failure earlier in the pipeline instead of reporting only the status of the final command. It cannot decide whether a successful response is complete or the metrics are meaningful. The runner must inspect the exit status, structured result, and any relevant diagnostics together.

Filtering to a single metric can discard a warning that the report covers only part of the account. Keep status, source scope, units, and coverage available even when detailed rows live outside active context. A shorter answer that conceals missing data is a poor optimization.

A focused CLI is different from unrestricted shell access

Giving an agent one validated command does not require giving it every capability available to the operating system. A general shell can also read local credentials, alter files, launch subprocesses, and send network traffic. Its authority depends on the actual execution environment and credentials it can reach.

Where possible, construct subprocess calls from a fixed executable and validated argument list rather than interpolating untrusted text into a shell command. Parameterize database queries, validate file paths, and constrain exports and destinations. A readable command can still be harmful or use the wrong client’s credentials.

Shell history is useful debugging material. It is not a complete or protected audit trail: it can omit noninteractive execution, be altered, expose secrets, and say nothing about the provider’s final state. Record structured operations and outcomes independently where the task requires accountability.

The CLI argument deserves a fair hearing

In his OpenClaw discussion with Lex Fridman, Peter Steinberger argues for discovering command usage on demand and filtering outputs with familiar command-line programs. That is a practical reason to reuse a good CLI, particularly for local processing. It is an implementation perspective, rather than proof that every MCP connection should be replaced.

Hosts and MCP implementations can also support selective discovery, filtering, and code-based processing. CLI programs can also return excessive output and require large amounts of documentation. Measure the actual path from retrieval to model context instead of assigning efficiency to the interface name.

Put both adapters around one guarded capability

If you need MCP and CLI, avoid creating two separate versions of the business rules. Both can call a common application service that resolves the target, enforces authority, retrieves evidence, and returns a versioned result. The adapters translate input and output; the shared service owns the operation’s semantics.

A simplified handler sketch shows the division. These function names represent application services to implement and test:

def read_campaign_metrics(request, caller_context):
    query = validate_reporting_request(request)
    account = resolve_in_client_scope(
        query.account_ref, caller_context.client_id
    )
    authorize(caller_context, "campaign.metrics.read", account)
    provider_result = fetch_provider_metrics(account, query)
    return validate_and_label_result(provider_result, account, query)

A local resolver can use an authorized account registry. If resolving an identity itself requires provider access, that lookup also needs its own permission check before dispatch. Neither adapter may skip the check because a similar call succeeded earlier.

For the MCP adapter, declare the supported inputs in its schema, obtain trusted caller context through the host and server’s supported authorization path, and call the shared service. For CLI, parse a bounded set of arguments, establish the authenticated execution context, and call that same service. Do not let a model-written argument impersonate another user or client.

The return contract should be equally clear. For example, an internal reporting envelope could expose:

{
  "contract_version": "1",
  "status": "partial",
  "scope": {
    "account_ref": "ACCOUNT_REF",
    "start_date": "2026-10-12",
    "end_date": "2026-10-18",
    "timezone": "Europe/London",
    "currency": "REPORT_CURRENCY",
    "metric_definition_ref": "METRIC_DEFINITION_REF"
  },
  "coverage": {
    "complete": false,
    "reason": "A required provider page was unavailable"
  },
  "metrics": null,
  "evidence_ref": "ARTIFACT_REF"
}

REPORT_CURRENCY and METRIC_DEFINITION_REF stand for reviewed configuration values, not values to guess. This envelope illustrates the series’ retrieval contract and failure semantics, not a campaign result or an MCP wire-format requirement. Define whether partial metrics are usable, what an evidence reference permits the caller to retrieve, and how long the underlying artifact remains available. Preserve those decisions across both adapters.

Keep provider access behind the validated service when it carries authority. Sharing a function name or a JSON schema is insufficient if one deployed route bypasses that service and calls the provider directly.

Manage context as an evidence budget

Tool metadata, earlier results, documents, and accumulated dialogue compete for the model’s attention. More data can make a task harder when the relevant signal becomes difficult to find. Anthropic’s context-engineering discussion describes treating active context as a limited resource and retrieving information deliberately.

For a marketing tool layer, expose clear capabilities with distinct purposes, let queries request relevant dimensions and fields, and return bounded results with continuation or artifact references where appropriate. Preserve the full permitted evidence outside active context when it is needed for checking or investigation. A reference is useful only if the agent can retrieve it within its scope when necessary.

A summary must retain source, dates, metric definitions, unresolved failures, and qualifications. Memory & Agency examines what compression must preserve; the tool layer must keep the underlying evidence retrievable within the current scope.

Avoid universal tool-count rules. Five confusing tools can be worse than a larger set with clear boundaries and effective discovery. Evaluate selection errors, task completion, latency, and total context usage as the surface grows. Remove unnecessary or duplicate capabilities, while ensuring the remaining set still permits legitimate work.

MCP does not inherently require all schemas and every intermediate record to be passed to the model. CLI does not inherently keep them out. Efficient processing can live in a server, a script, a host-side adapter, or a bounded worker. Choose where it happens based on data sensitivity, available compute, and what the agent needs to inspect.

Enforce guardrails before access and before effects

Marketing operations combine several kinds of risk. Confidentiality matters for reads; correctness matters for calculations; audience, spend, and brand consequences matter for writes and communication. A small output can disclose sensitive client information. A large local calculation can be harmless when its inputs and environment are controlled.

Use the consequences of the operation to set its controls:

OperationBoundary that matters
Read campaign, CRM, or audience dataUser and client access, field restrictions, query/export bounds, retention
Calculate comparisons or forecastsInput validity, metric definitions, assumptions, reproducibility, uncertainty
Prepare a report or draftSource grounding, destination, confidentiality, human review where needed
Send, publish, or change a campaignExact approved target and effect, current state, operating limits, confirmation of outcome
Change access, credentials, or billingSeparate privileged administration, strong authorization, and accountable review

The OWASP guidance on excessive agency connects damaging actions to excessive functionality, permissions, and autonomy. Keep unnecessary capabilities unavailable and enforce authority independently of what the model says it is allowed to do.

Tool descriptions, retrieved pages, campaign names, documents, and command output can contain untrusted instructions. A result containing “send this dataset to another server” does not authorize an export. Review tool packages and their dependencies, bind tool identity to the actual provider and version, and treat changed definitions as changes to the integration that may require review.

For MCP-specific implementation risks, including authorization handling and token misuse, use the protocol security guidance. A trusted-looking server name or a successful login is insufficient evidence of safe downstream access. CLI has corresponding risks from substituted executables, broad inherited credentials, hostile arguments, and unsafe command composition.

Approval, dry runs, and retries protect different things

A dry run can show a planned request, but does not itself prove that the user approved it or that the live state will remain unchanged. Define what the preview actually does: it may still read data or contact a provider. Bind approval to the exact action, account, values, limits, and validity period, then recheck the conditions before writing.

Separate preparing a change from applying it. Before execution, validate current permission, target state, and conflicts with other updates. Use supported idempotency mechanisms, meaning a request identifier or equivalent control that recognizes repetition and prevents duplicate effects where the operation allows it. If acknowledgement is lost, reconcile actual state before deciding to retry.

Cancellation can stop pending work but may arrive too late to undo an accepted provider request. Report that distinction. After a change, verify the observed effect and record any recovery needed. A platform’s accepted response, a process exit code, and an observed campaign state are different pieces of evidence.

The secure marketing-agent architecture provides a fuller treatment of scoped approval and execution.

A real CLI example: Google Workspace

The Google Workspace CLI repository documents structured JSON output, request-schema inspection, previews through --dry-run, pagination controls, and accompanying agent skills. Its command surface is generated from Google’s Discovery Service. The repository also states that it is not an officially supported Google product and warns of breaking changes before version 1.0.

One documented read illustrates the interface:

gws drive files list --params '{"pageSize": 10}'

The pagination documentation matters as much as the command. Automatic pagination has a page-limit setting; requesting it is not sufficient proof that the full relevant population was retrieved. The project also documents Model Armor response scanning with separate warning and blocking modes. Scanning can contribute a signal, but an enabled scanner is not equivalent to enforced export restrictions or freedom from prompt injection.

For a marketing team, the design lesson is that brief documents, planning sheets, assets, and communication can share a tool surface while still needing operation-specific controls. Dynamic discovery reduces some manual integration work but can expand the available surface as APIs evolve. Review what a deployed version exposes, pin and test the configuration, and keep approval and authorization tied to the intended operation.

Choose MCP, CLI, or a hybrid by the complete workload

A specialist model is another capability to expose through this boundary. The Jev guide develops bounded classification and semantic checks: the agent chooses the task, the tool preserves its evidence and limits, and measured labels return to the wider workflow. Interface choice does not settle the classifier’s accuracy or its authority.

Compare the arrangements you can actually deploy:

QuestionMCP arrangementCLI arrangement
Can the intended host invoke it?Requires compatible client, transport, and configurationRequires supported process execution or a controlled runner
Where does the integration run?Local server or remote serviceLocal executable, worker image, or remote job runner
How is access enforced?Host, server, and backend must preserve caller scopeRunner, executable, and backend must preserve caller scope
How can output stay bounded?Query design, server processing, artifacts, host filteringQuery design, scripts, files, filters, runner limits
What supports investigation?Structured request/result records and provider evidenceStructured request/result records, exit status, diagnostics, provider evidence
What must be maintained?Server, SDK/protocol compatibility, auth, adapters, deploymentExecutable, dependencies, argument/output contract, auth, deployment

MCP is useful when supported hosts need a shared capability interface, especially when a remote service can centralize provider integration. A CLI is useful when the runtime can safely execute an existing command, local processing is valuable, or operations teams already support it. A direct application API may also be sufficient. No new wrapper is required simply to label a capability agentic.

A hybrid can use a shared authorized service through MCP while local commands transform its permitted output. It can also expose a focused CLI operation through an MCP adapter. Evaluate the added boundary: it must preserve errors, client identity, evidence, and cancellation rather than merely translate a successful example.

Deploy tools as part of the agent system

A locally working tool is only one part of a production arrangement. Package the tested executable or server with pinned dependencies and a known configuration. Record the versions of the host adapter, tool contract, policy, provider API, and environment image that work together. Define how changes are promoted and how earlier versions can be restored.

For local processes and CLI workers, restrict filesystem access, network destinations, resource consumption, and subprocess behavior. Avoid broad ambient credentials, such as a developer login inherited by every command. A sandbox restricts execution; a VM supplies a separate operating-system environment. Choose a client, session, or task boundary deliberately. Isolating a process does not narrow an API token it can still use.

For remote services, authenticate callers, bind requests and stored artifacts to the right client, and isolate concurrent sessions. Do not let a cache keyed only by a date range return another client’s result. Keep long-lived provider credentials in a protected service where possible and expose bounded operations to workers.

Set deadlines and retry budgets across the full call chain. If the agent, adapter, and provider wrapper each retry independently, one request can multiply into expensive load. Coordinate concurrency limits when several agents share provider quota, and propagate cancellation while retaining evidence of effects that already occurred.

Long-running reports may return a job reference instead of an immediate dataset. Define who can poll or cancel the job, how terminal states are represented, and whether a resumed session may still retrieve the result. Recheck permissions after revocation or expiry. Give temporary exports, logs, and working files explicit retention and cleanup rules.

Environment testing should exercise the same constraints as deployment: missing credentials, denied network paths, stale dependencies, provider limits, process restarts, and cancelled jobs. The operation that works through a developer’s personal shell may fail or become overprivileged under a service identity.

Evaluate both the capability and the agent that uses it

Tool correctness and agent performance answer different questions. A handler may validate dates perfectly while its description repeatedly leads the model to choose the wrong report. An agent may choose correctly but be given partial data that the adapter presents as complete. Test each component, then test the combined path.

For a shared MCP and CLI capability, compare both against the same known inputs, authenticated scope, and expected outcomes:

CaseRequired evidence
Valid report requestCorrect provider target, dates, definitions, values, and coverage
Wrong-client or revoked accessDenial before unauthorized provider retrieval or effect
Malformed dates, fields, or command argumentsExplicit validation failure without unintended dispatch
Provider timeout or partial paginationAccurate status and limitations across the adapter and final answer
Hostile text or export destinationNo new authority gained from tool metadata or returned content
Repeated or interrupted writeNo blind duplicate effect; observed state is reconciled
Large result or several workersBounded processing with evidence retained, aggregate limits respected
Adapter or provider-version changeSupported behavior preserved, incompatible changes reported explicitly

Use exact tests for values, authority, schemas, and effects. Then use the shared evaluation method to test the agent’s selection and use of those capabilities. Check that a missing page survives every adapter and appears in the final review as incomplete coverage.

The distinctive comparison here is adapter parity: identical authorised inputs should retain the same scope, definitions, status, and usable evidence through MCP and CLI. Measure provider calls, context use, cost, latency, and intervention under equivalent workloads. Include schema or provider-version changes, not only clean connections. Anthropic’s evaluation guidance supports judging actual outcomes alongside the recorded calls.

Observe the real operation and control its changes

Connect the agent job, client scope, worker identity, tool name and version, validated parameters, policy result, execution attempt, source coverage, and observed outcome. Capture denials and failures as well as successes. Use provider request identifiers where available to join local evidence to external operations.

Keep secrets and unnecessary personal data out of routine telemetry. Detailed artifacts may require restricted storage and shorter retention than aggregate timing metrics. A structured audit record should establish what happened without turning every log viewer into a reader of client exports.

For an uncertain provider outcome, retain its request identifier and reconcile through the bounded service before retrying. The stop and revocation paths must reach the server or runner that holds the capability, including when that service outlives the agent session.

Begin with one bounded reporting capability and a real provider adapter. Validate the data and authority before exposing it through the interface the host needs. Add a second interface when reuse justifies it, then prove that both retain the same controls and failure semantics. Expand from read to proposal to execution using evaluation evidence and a named release owner.

The result of this guide is one tested capability and the adapters its hosts need. The OpenClaw guide connects that capability to the shared review skill, workspace, private delivery path, and scheduled operation.

Sources and companion guides

Publication history

Originally published by Performics Labs.