Building AI Agent Skills: A Practical Engineering Guide to Design, Permissions, and Production Governance

    Many teams can connect an AI agent to tools, but few can ship agent capabilities that are reliable in production. This guide explains what separates a true "skill" from a simple tool call, and walks through the full engineering lifecycle: defining input/output contracts, structuring a production-grade skill package, evaluating third-party skills, building a minimal working skill skeleton, designing least-privilege permissions, orchestrating sub-agents, controlled dynamic context injection, and a phased rollout plan. It also includes a sample agent skill stack, governance mechanisms, and a pre-launch checklist to help teams turn agent demos into sustainable production capabilities.

    Building AI Agent Skills: A Practical Engineering Guide to Design, Permissions, and Production Governance

    1. Why “Being Able to Call Tools” Is Not the Same as “Having Skills”

    Most teams building agents go through two phases. The first version stuffs every workflow into the prompt; the second version wires up a set of tool interfaces so the model can query, write, or trigger tasks. The first approach looks great in demos but breaks down in real business scenarios: unstable steps, missing error handling, blurry permission boundaries, and unreproducible results. The second approach improves the agent’s ability to act, but if you merely expose interfaces to the model, you still only have “the ability to call,” which falls well short of “a deliverable skill.”

    In this article, a skill is defined as a unit of capability that an agent can discover, load, execute, evaluate, and govern. It is not a single prompt, nor a single API endpoint. It is an engineered package containing usage instructions, input/output contracts, tool boundaries, execution flow, permission policies, failure handling, test cases, and observability information. A mature skill answers six questions clearly:

    1. When to use it: trigger conditions, applicable scenarios, and prohibited scenarios.
    2. What inputs are required: fields, types, sources, trust levels, and how to degrade gracefully when data is missing.
    3. What it may do: permitted tools, read/write scope, network and file boundaries.
    4. What steps it follows: a reproducible process, exception branches, retry and termination conditions.
    5. How to judge whether results are reliable: validation rules, cited evidence, confidence levels, and human review points.
    6. How to trace problems: audit logs, distributed tracing, version numbers, and responsible owners.

    Only when these questions are explicitly codified can a skill evolve from “personal experience” into “a team asset.”

    2. Clarifying Concept Boundaries: Skill, Tool, Prompt, Workflow, and Sub-agent

    In practice, a common mistake is calling everything an “agent” or a “skill.” To keep systems from becoming needlessly complex, align on the concepts first.

    Concept Core Role Typical Boundary
    Prompt Expresses task intent, constraints, and output requirements to the model Does not enforce permissions or guarantee process stability
    Tool An atomic operation, e.g., query logs, read a file, run a search Performs a single action; should not embed complex business decisions
    Skill A reusable capability package oriented around a business goal, combining instructions, tools, flow, and evaluation Has input/output contracts, permission boundaries, and a lifecycle
    Workflow Explicit state transitions, node orchestration, and failure recovery Emphasizes deterministic processes; can invoke skills and vice versa
    Sub-agent A delegated executor with a specific role, independent context, and its own policies Suited for task decomposition, isolation, and review; should not recurse indefinitely

    A sound design principle: keep tools atomic, let skills carry business semantics, use workflows to guarantee determinism for critical steps, and use sub-agents to isolate complex reasoning or parallel tasks. For example, “query logs” is a tool; “diagnose a production error and propose a fix” is a skill; “diagnose first, then run a security review, then generate a change ticket” is a workflow; and the “security reviewer” can be a sub-agent.

    3. The Basic Structure of a Production-Grade Skill

    A maintainable skill package should include at least the following. Different runtimes may use different directories and fields, but the design philosophy is the same.

    1. Metadata and versioning

    Include the skill identifier, owner, version number, compatibility scope, applicable tenants, cost tier, and change log. Versions should follow semantic versioning: bug fixes increment the patch version, new backward-compatible capabilities increment the minor version, and breaking changes to input/output contracts increment the major version. Without version numbers, canary releases and rollbacks become nearly impossible.

    2. Usage instructions and counter-examples

    Documentation must state both “when to use” and “when NOT to use.” Capability descriptions alone are insufficient—counter-examples significantly reduce false triggers. For instance, a “log diagnosis skill” is suitable for read-only analysis and should never modify production configuration without approval; when a user requests cross-tenant queries, the skill should refuse or escalate to an authorization workflow.

    3. Input and output contracts

    Input fields should define types, whether they are required, their source, masking requirements, and validation rules. Outputs should use a structured format, e.g., a summary, an evidence list, a hypotheses list, recommended next steps, a confidence score, and an audit identifier. Structured outputs make downstream orchestration, testing, and monitoring easier, and they reduce “plausible-sounding but non-executable” answers.

    4. Tool allowlists and resource boundaries

    A skill should not have full access to the runtime environment by default. Bound it across four dimensions: action, resource, tenant, and time window. For example, allow reading only the last 30 minutes of logs for a specified service, allow access only to the current tenant’s knowledge base, and allow only read-only APIs. Write, delete, and publish operations should be disabled by default or require human approval.

    5. Execution flow and failure strategy

    The flow should cover parameter validation, permission checks, tool calls, result validation, masking, and audit writes. For timeouts, empty results, unavailable data sources, and non-compliant model outputs, define explicit degradation strategies. Retries must have upper limits, and automatic retries must never be applied to non-idempotent operations.

    6. Test and evaluation cases

    Prepare at least three categories of tests: the normal path, boundary inputs, and adversarial inputs. The normal path validates functionality; boundary inputs test empty values, overly long contexts, and cross-tenant requests; adversarial inputs test prompt injection, malicious documents, forged tool results, and sensitive-information leakage.

    7. Observability and auditing

    Record the skill version, caller, tenant, input digest, tools used, key parameter hashes, output digest, latency, cost, error codes, and any human intervention. Sensitive fields must be masked, and raw logs and audit logs should have tiered access controls.

    Below is an illustrative configuration. The fields are for structural explanation only; map them to your actual runtime’s format in production:

    1. id: service.log_diagnosis
    2. version: 1.2.0
    3. owner: platform-team
    4. description: Read-only analysis of error logs for a specified service within a time window, with troubleshooting recommendations
    5. activation:
    6. when:
    7. - user describes a production error or abnormal metrics
    8. - service name and time window are provided
    9. not_when:
    10. - request involves configuration modification or deletion
    11. - unauthorized cross-tenant query
    12. inputs:
    13. required: [tenant_id, service_name, time_window, symptom]
    14. optional: [trace_id, environment, runbook_ref]
    15. outputs:
    16. schema: diagnosis_result_v1
    17. permissions:
    18. - action: logs.read
    19. resource: current_tenant.service
    20. mode: read_only
    21. - action: metrics.read
    22. resource: current_tenant.service
    23. mode: read_only
    24. tools:
    25. - query_logs
    26. - query_metrics
    27. policy:
    28. max_tool_calls: 6
    29. max_duration_seconds: 45
    30. human_approval_required_for_write: true
    31. observability:
    32. trace: true
    33. redact: [token, secret, personal_data]
    34. eval:
    35. suites:
    36. - normal_cases
    37. - empty_result_cases
    38. - prompt_injection_cases

    4. Where to Find Reliable Skills: Don’t Judge by Popularity Alone

    Skills typically come from three sources: internal team registries, organization-level shared marketplaces, and the open community. Prioritize internal sources because permission, data, and ownership boundaries are clearer. External sources can serve as inspiration, but they must undergo a secondary review before entering production.

    To evaluate whether a skill is worth adopting, use seven dimensions: fit, security, quality, maintainability, observability, portability, and cost:

    1. Business fit: Can the inputs and outputs be mapped onto existing processes? Does it address a frequent, real need rather than merely showcasing model capabilities?
    2. Security boundaries: Does it default to least privilege? Does it support tenant isolation, data masking, auditing, and human approval?
    3. Test quality: Is there a reproducible evaluation set? Are failure paths and adversarial inputs covered?
    4. Maintainability: Are versions clear, dependencies transparent, and interface changes documented with migration notes?
    5. Observability: Can it record tool calls, latency, errors, and cost? Does it support distributed tracing?
    6. Portability: Is business logic overly coupled to a specific runtime? Are underlying tools easy to replace?
    7. Cost and latency: Are tool call counts, context lengths, and model turns controlled? Are there caching or batching strategies?

    High popularity does not mean production-ready. Watch out for these warning signs: overly broad permission declarations, missing tests, opaque dependencies, secrets or sensitive data embedded in prompts, unrestricted network egress, no owner, no version history, frequently changing output formats, and documentation that only showcases success stories. A safer approach is to maintain a skill admission scorecard; anything below the threshold goes to sandbox trials only, never into the production registry.

    5. Build a Working Skill Skeleton in 10 Minutes

    “10 minutes” is enough for a minimal closed loop, not a production deliverable. Pick a narrow scenario, such as “read-only diagnosis of error logs for a specified service over the last 30 minutes.”

    Step 1: Constrain the scope

    Accept only a service name, time window, symptom description, and tenant identifier as input; produce only error clusters, evidence, possible causes, next-step recommendations, and an audit identifier. Explicitly exclude configuration changes, cross-tenant queries, and reading secrets.

    Step 2: Define the contract

    Write the data structure before writing the implementation. Outputs must be machine-validatable, for example:

    1. {
    2. summary: string,
    3. evidence: [{source, timestamp, excerpt, trust_level}],
    4. hypotheses: [{cause, confidence, verification_step}],
    5. next_actions: [string],
    6. audit_id: string
    7. }

    Step 3: Implement the minimal execution chain

    The pseudocode below emphasizes the flow rather than any platform-specific interface:

    1. function runSkill(input, context):
    2. validate(input)
    3. assertTenantScope(input.tenant_id, context.actor)
    4. scope = buildReadScope(input.service_name, input.time_window)
    5. logs = context.tools.queryLogs(scope, limit=...)
    6. metrics = context.tools.queryMetrics(scope, indicators=[...])
    7. clusters = deterministicCluster(logs, metrics)
    8. evidence = extractEvidence(clusters, maxItems=...)
    9. sanitized = redact(evidence)
    10. result = context.model.generateStructured(
    11. template="log_diagnosis",
    12. evidence=sanitized,
    13. outputSchema=diagnosis_result_v1,
    14. maxTurns=3
    15. )
    16. validateSchema(result)
    17. attachAuditId(result, context.audit.create(...))
    18. return result

    Step 4: Validate quickly with test cases

    Do not rely on a single manual test. Prepare at least five input categories: normal errors, empty logs, an excessively long time window, cross-tenant requests, and log text containing malicious instructions. The validation goal is not whether the final answer “looks smart,” but whether it conforms to the contract, refuses unauthorized access, provides evidence, and controls tool call counts.

    Step 5: Complete the pre-production checklist

    Ten minutes gets you a skeleton. Before production, add permission policies, masking, auditing, timeouts, retries, budget controls, an evaluation set, and a rollback plan. In particular, external documents and log content must be treated as untrusted input—their presence in context must never grant them the power to change system policies.

    6. Permission Design: Turning “Able to Call” into “Controllably Called”

    Permissions are the lifeline of a skill system. Follow these principles:

    1. Least privilege and action tiering

    Tier actions into read, write, delete, publish, and authorize. Default to read-only. Write operations must explicitly declare resource scope and human approval conditions; delete and publish operations require secondary confirmation, an approval flow, and a rollback path.

    2. Tenant isolation and data classification

    Validate the relationship among caller, tenant, and resource on every invocation. The tenant identifier in the input must come from a trusted identity context and must not be freely modified by the model. Classify data into public, internal, sensitive, and strictly confidential tiers; skills declare the maximum tier they may process and mask outputs accordingly.

    3. No secrets in prompts

    Model context is not a credential store. Credentials needed for tool calls should be obtained through a controlled credential broker or short-lived tokens—never concatenated into prompts, logs, or skill documentation. Audit logs must not retain raw tokens either.

    4. Sandboxing and egress control

    Execution environments should restrict the file system, network egress, and system call scope. Use allowlists for external access. For skills that need internet access, explicitly define permitted domain categories, data masking requirements, and response validation policies—do not open access by default.

    5. Human in the loop

    High-risk actions should require human confirmation, such as modifying production configuration, sending external notifications, deleting data, or changing permissions. The confirmation page should present a structured change summary, impact scope, supporting evidence, and a rollback plan—not just a one-sentence natural-language conclusion.

    6. Audit and traceability

    Audit records must answer: who, at what time, under what identity, had which version of which skill access which resources, invoke which tools, produce what result, and whether human approval was involved. Audit data itself needs access controls and retention limits.

    7. Sub-agents: When to Split and How to Collaborate

    More sub-agents is not automatically better. Good reasons to split include: the task requires different specialist roles, needs context isolation, benefits from parallel investigation, requires independent review, or needs to restrict a role’s tool permissions.

    Three common collaboration patterns:

    1. Plan–execute–review: the main agent plans, sub-agents execute specialized steps, and a reviewer agent checks evidence and security boundaries.
    2. Parallel investigation: logs, metrics, configuration, and code changes are analyzed by separate sub-agents, then merged by an aggregator.
    3. Tiered routing: simple tasks are handled directly by the main skill; complex tasks are routed to expert skills, so not every skill shares one bloated context.

    Sub-agents need explicit task contracts: goal, input structure, available tools, permission scope, deadline, budget, and return format. Shared information should pass via structured artifacts rather than copying full conversations. Every sub-agent should inherit least privilege—the main agent having write access must not automatically grant the same to its sub-agents.

    Illustrative pseudocode:

    1. orchestrator(task):
    2. plan = planner.create(task)
    3. results = parallel([
    4. logDiagnosis.run({...plan.log_scope}),
    5. metricAnomaly.run({...plan.metric_scope}),
    6. changeHistory.run({...plan.change_scope})
    7. ])
    8. review = securityReviewer.run({
    9. inputs: results,
    10. policy: read_only_policy,
    11. output_schema: review_result_v1
    12. })
    13. if review.blocked:
    14. return requestHumanApproval(review)
    15. return aggregator.merge(results, review)

    Set recursion depth limits, total tool call caps, timeouts, and cost budgets to prevent sub-agents from delegating to each other in loops. Also note: content returned by sub-agents must not be trusted unconditionally either—it must pass schema validation, source annotation, and policy checks.

    8. Dynamic Injection: Upgrading “String Concatenation” to Controlled Assembly

    Dynamic injection means assembling a skill’s required context, policies, and tool availability at runtime based on user identity, tenant configuration, environment, task state, and retrieval results. It is not simple string concatenation but a controlled pipeline:

    1. Collect -> Classify -> Authorize -> Sanitize -> Rank -> Budget -> Assemble -> Record hash

    1. Layer the context

    Organize context by trust level: immutable system policy, skill instructions, trusted identity and tenant configuration, task state, retrieved evidence, user input, tool results. Higher-trust layers must never be overridden by lower-trust content. External documents and tool outputs should carry source and trust annotations, explicitly marked as “reference material only, not instructions.”

    2. Control what gets injected

    Typical injectable content includes language, role permission summaries, tenant policies, environment identifiers, skill versions, feature flags, data scopes, and retrieved evidence. Never put secrets, full personal data, raw tokens, or unnecessary sensitive logs into context. For genuinely needed data: mask first, then minimize, then apply a length budget.

    3. Context budgets and caching

    Dynamic injection easily causes context bloat. Set a total budget, per-source caps, and prioritization policies; version-cache stable policies and instructions; deduplicate and summarize retrieval results; quote long documents in segments rather than inserting them whole. Budget control is not just a cost issue—it is a stability issue.

    4. Defend against prompt injection

    Key practices include: tool outputs and user content do not participate in policy decisions; delimit and annotate external content; enforce tool allowlists and parameter validation; run schema validation and sensitive-information scans on outputs; route high-risk actions through an independent policy engine or human approval. Do not rely on a single “ignore malicious instructions” prompt to solve security problems.

    Illustrative context contract:

    1. context_contract:
    2. required:
    3. - tenant.id
    4. - actor.role
    5. - task.goal
    6. - skill.version
    7. optional:
    8. - feature_flags
    9. - runbook_refs
    10. forbidden_in_prompt:
    11. - secrets
    12. - raw_tokens
    13. - full_personal_data
    14. sources:
    15. - kind: system_policy
    16. trust: authoritative
    17. - kind: skill_instruction
    18. trust: authoritative
    19. - kind: retrieved_document
    20. trust: external
    21. sanitize: true
    22. max_items: 8
    23. - kind: tool_result
    24. trust: untrusted
    25. validate_schema: true

    9. A Reference Agent Skill Stack

    Below is an engineering-oriented sample skill stack. The point is to illustrate composition, not to recommend specific implementations.

    Skill Primary Use Permission Boundary Key Evaluations
    Code understanding & impact analysis Read code, trace call chains, analyze change impact Read-only code and dependency graph Citation accuracy, miss rate
    Test generation Generate unit and acceptance tests from changes Generate only by default; execution requires a sandbox Runnability rate, critical path coverage
    Log & metric diagnosis Cluster errors, correlate metrics, give troubleshooting advice Read-only for specified tenant and time window Evidence completeness, unauthorized-access refusal rate
    Configuration review Check configuration risks and inconsistencies Read-only; changes require approval Rule hit rate, false positive rate
    Release guard Pre-release checks of change tickets, test results, rollback plans Read-only checks; does not release directly Block accuracy, human review volume
    Data query explanation Explain structured query results as business conclusions Read-only, row-level permissions, masked output Consistency of definitions, traceable citations
    Documentation & runbook generation Generate guides, troubleshooting manuals, change summaries Writes to a controlled document space only Factual consistency, link validity
    Security & compliance review Check sensitive data, permissions, and external input risks Read-only review, outputs risk levels False negative rate, policy coverage
    Evaluation & review Check sub-agent results for evidence and run counterexample tests Read-only access to results and logs Agreement with human review

    The core ideas of this stack: “read more than write, separate generation from execution, and require human confirmation for critical actions.” Code generation skills never auto-commit; the release guard never releases directly; data queries default to read-only; security review is independent of business execution. Every skill needs its own evaluation set and owner, rather than one “do-everything agent” bearing all responsibilities.

    10. Engineering Governance: Keeping Skills Evolvable

    The real work begins after launch. Establish these mechanisms:

    1. Registry: centrally register skill identifiers, versions, owners, permissions, input/output contracts, and compatibility.
    2. Continuous evaluation: run a regression set on every change, covering normal, boundary, adversarial, and security cases; gate releases on evaluation results.
    3. Canary releases: enable new skills on small tenants or low-risk tasks first, observe success rates, human takeover rates, error rates, and cost, then expand gradually.
    4. Observability: record skill versions, tool call chains, latency, cost, error codes, and policy rejection reasons. Set alerts on critical skills.
    5. Rollback: keep the last stable version and configuration, and roll back quickly on contract incompatibility or cost anomalies.
    6. Cost control: set max turns, max tool calls, context budgets, and timeouts; cache repeated queries and rate-limit batch tasks.
    7. Security operations: periodically review permissions, egress allowlists, log masking, and approval records; retire unused or unmaintained skills.

    When deploying on the cloud, common infrastructure such as object storage, logging services, monitoring and alerting, container platforms, and message queues can host skill packages, execution environments, audit data, and asynchronous tasks. Baidu AI Cloud offers comparable general-purpose capabilities and can be one option in your evaluation, but the actual choice should depend on your organization’s compliance requirements, costs, existing tech stack, and operations capability—do not introduce unnecessary complexity just for the sake of “moving to the cloud.”

    11. Rollout Path: From a Single Closed Loop to Systematic Operations

    Phase 1: Pick a high-value, low-risk scenario

    Prioritize read-only, verifiable, frequent tasks such as log diagnosis, change impact analysis, or document Q&A. The goal is to complete the loop of input contract, tool calls, structured output, auditing, and evaluation.

    Phase 2: Add permissions and quality gates

    Add tenant isolation, masking, timeouts, retries, budgets, and regression tests to skills; establish human confirmation mechanisms; bring skills under version management and release processes.

    Phase 3: Introduce sub-agents and dynamic injection

    Split expert sub-agents only when tasks start to involve multiple roles, multiple data sources, and long contexts. Implement dynamic injection as a controlled pipeline: solve source annotation, budgets, and injection defense first, then expand context scope.

    Phase 4: Platformize

    Build a skill registry, evaluation pipeline, monitoring dashboards, and permission governance processes. Let business teams reuse base skills while a platform team centrally owns security policies, runtime environments, and cross-team coordination.

    12. Pre-Launch Checklist

    Before putting a skill into real business use, confirm at least the following:

    1. Are applicable and prohibited scenarios clearly documented?
    2. Do inputs and outputs have stable contracts and version numbers?
    3. Are only necessary permissions requested, and is tenant isolation supported?
    4. Do write, delete, and publish operations require human approval?
    5. Are tool outputs and external documents treated as untrusted content?
    6. Are there timeouts, retry caps, cost budgets, and failure degradation paths?
    7. Are there normal, boundary, and adversarial test cases?
    8. Can you trace versions, call chains, evidence sources, and human interventions?
    9. Are owners, maintenance cycles, and rollback plans clearly defined?
    10. Has the skill passed a joint review by security, compliance, and business stakeholders?

    Conclusion

    An AI agent’s competitive edge ultimately lies not in “whether the model can answer,” but in “whether its skills are discoverable, composable, authorizable, evaluable, and governable.” A well-designed skill should be like a reliable component in an engineering system: clear boundaries, stable contracts, minimal permissions, traceable evidence, and recoverable failures. Start by closing the loop on a small, well-defined scenario, then gradually introduce permission policies, sub-agents, and dynamic injection. That is how teams move agents from demo tools to genuinely operational production capabilities.