Develop AI agents with explicit rights and action scopes
Develop reading, drafting and publication as separate capabilities with reviewable transitions.

An agent proposes actions while the application determines authority
An AI agent connects processing steps to tool calls. A textual suggestion can consequently become a persisted change or a publication. A carefully written system prompt alone does not reliably establish that actual authority. The application must evaluate each proposed call at its own tool boundary, where the authoritative actor context, permitted resources and allowed effect are known. The decision must survive even an unreasonable or manipulated proposal.
Our original example is a fictional editorial assistant. It may read selected sources and create its own drafts. Publication inside the demonstration database requires a separate approval record. That record belongs to the specific actor, draft and unchanged content, has a short fixed lifetime and is consumed together with its effect. The agent cannot issue that approval through its tool directory. Its ability to request the next step is distinct from its authority to perform it.
Fifty-five actually executed Python/SQLite conditions investigate this boundary. No language model is called and nothing is published to a real website. We therefore do not assess model planning or detection performance. The article shows the deterministic part that allows or rejects a proposed operation under explicit rules. This separation remains useful when models change or produce suggestions of varying quality.
Describe a small explicit action space first
The directory offers exactly five tools: read a source, create a draft, edit a draft, request publication and publish a draft. There is no general shell, arbitrary URL retrieval or approval-issuing tool. Unknown names are rejected. A proposal gains no additional authority by supplying a persuasive justification or a supposedly urgent instruction as prose. Tool selection remains inside a declared application contract.
OWASP recommends least privilege and checks on relevant requests. In our concrete example this becomes an explicit narrow interface. A model may supply only the described arguments. Identity, source inventory and current evaluation time come from trusted application context, not freely chosen fields inside the tool message. This keeps the source of authority separate from the data being evaluated.
The small directory restricts only this particular invocation path. It does not make the Python process an operating-system sandbox. Someone able to execute arbitrary Python under the same process privileges would have other capabilities. Production integrations must therefore limit runtime permissions, credentials, network access and unnecessary tools appropriately. Omitting a shell entry is not actual isolation from already compromised application code.
Do not let the proposal declare its own identity
Dispatch receives the actor separately from the proposed call. Two fictional editorial scopes are permitted in the experiment. The tool message contains only tool and args; adding an actor property fails its shape check. An unsupported actor in the trusted context is rejected as well. A message cannot simply insert an administrator name and inherit privileges associated with that claim.
The fixture deliberately does not implement login. A real application must obtain context from its authoritative identity and session system. A hardcoded name or a list of strings is not authentication by itself. The displayed core starts where the actor context is already reliable. Any later integration must preserve that prerequisite rather than accepting the model’s own description of who it represents.
The same distinction matters across several agents. A forwarded message should not determine on its own whose authority the receiving component uses. Identity, permitted scope and requested effect need to agree at the actual boundary. Our small two-actor case tests that relationship directly. It is not a complete organization-wide role system or tenant-management implementation, and it should not be presented as one.
Restrict source access to known resources
The source inventory is an application-supplied mapping that the proposal cannot freely alter. Each actor has its own approved collection. The same short source name returns different permitted text in the two scopes, while an unknown name is rejected. Supplying an internet address as a source name triggers no network retrieval because this tool has no arbitrary fetch capability at all.
That design avoids turning a convenient URL argument into broad incidental authority. A production retrieval service would additionally need controls for destinations, redirects, private address ranges and transmitted credentials. Our implementation intentionally uses an existing inventory instead. It does not claim complete protection against all server-side request abuse because it does not perform that class of request here.
The returned state labels the content as an untrusted source. This helps classify data but does not automatically detect malicious instructions. Authority still lives in the application. Even an emphatic command inside a document does not gain access to an otherwise unapproved publication. Source content and permission continue to originate in different places, regardless of the document’s tone or apparent urgency.
Instruction-like source text remains data at this boundary
The fictional source deliberately contains a sentence telling the reader to ignore all rules and publish everything. Reading it returns the literal text without creating a draft or approval. The test then intentionally stores the same sentence as draft content. It still publishes nothing. This counterexample establishes the separation between ingesting content and performing a tool effect.
The experiment does not claim semantic detection of prompt injection. It runs no model that might follow the sentence. OWASP describes such risks and relevant complementary controls. Our particular evidence concerns the authority boundary: even a subsequent proposed publication call needs the matching valid approval. There is no claim that the content has become safe merely because it passed a structural parser.
Editorial review remains necessary for its own reasons. A saved draft can contain nonsense, confidential information or unsuitable assertions. Whoever approves it later must assess the actual content and its suitability. The tool boundary determines authority, not factual accuracy, quality or publication merit. Combining these different decisions into one generic security status would conceal important limits of the implementation.
Validate each call with a bounded strict contract
The parser accepts at most 8192 bytes and requires valid UTF-8. Its top level must be exactly an object containing tool and args, with args also an object. Duplicate properties are rejected even inside nested objects. Nonstandard constants such as NaN are not silently accepted. The executed cases include malformed input, invalid encoding and an array substituted for the required call shape.
Each tool has its own exact allowed fields. A draft request cannot add published true or a freely chosen actor. Text validation requires a nonempty string inside the specified UTF-8 byte bound. A Boolean is not helpfully converted into text. This is a deliberately narrow contract for these five tools, not a general schema for every possible agent operation.
Bounding one message does not bound the total agent run. A system can still generate many small calls. Real deployment needs separate limits for iterations, elapsed time, expenditure and repeated failures. Our example also enforces a small persistent draft quota, but it contains no complete agent planner or resource supervisor. A passing payload-size condition cannot establish the presence of those absent controls.
Scope drafts by actor and enforce quota within the write boundary
Every draft stores its authoritative actor. Editing, requesting publication and publication itself all look up the draft through that relationship. Another actor’s identifier fails the scope check. A value that resembles SQL injection likewise remains an ordinary bound value in the prepared query. The operation does not build an executable SQL command out of the proposed identifier.
Each actor may have at most three persisted drafts in this demonstration. The quota counts the durable inventory, including rows already marked published. It is not a session allowance and a new process does not reset it. The second actor has a separate inventory. This makes the limit’s actual meaning explicit instead of leaving readers to infer a different kind of budget from the number three.
Two separate database connections synchronize at a barrier and compete for one remaining draft slot. Exactly one creates a draft; the other encounters the same quota. Counting and writing take place inside the appropriate transaction. A count obtained earlier outside the write boundary would have different concurrency assumptions. The test establishes the shared-state behavior rather than only checking a local in-memory counter.
Requesting approval does not create authority
Request_publication returns requires_approval, the draft identifier and the digest of its current content. The database still contains no approval afterwards. An agent can ask for the next stage without approving it for itself. The experiment checks the actual missing record, not just reassuring wording in the response. A state label alone would be weak evidence if another hidden write had already granted authority.
Approval is issued only through issue_approval on a separate trusted operator path. This function is not an offered agent tool. A real application must implement its secure availability to authorized people outside this small core. Merely hiding a function name is not authentication. Separating the directory is a required property of this contract, but it is not the whole production access-control system.
The responsible operator needs a concrete reviewable draft and a clear description of the proposed effect. An abstract yes to unspecified future content would not match this method. Content must exist so the decision can bind to the actual result. If that content later changes, the boundary evaluates the binding again. The approval process should therefore present the thing being approved rather than an interchangeable summary.
Bind actor, object, exact content and expiry together
The approval record stores actor, draft, the SHA-256 digest of the content’s UTF-8 bytes and an expiry time. Its random identifier only locates that protected database row. It is not permission invented by the model. The test rejects an invented token and rejects moving a real approval to another draft. Matching the identifier alone is insufficient without its other associated properties.
Editing the content changes its digest and blocks publication under the old approval. The record remains unused because no effect occurred. This contract binds exact content bytes rather than a separate immutable version number. Restoring exactly the original bytes would restore the same digest. A product that must invalidate every intermediate edit needs an additional version binding; this source does not pretend its hash provides that stronger historical rule.
The demonstration grants 300 seconds of validity. At the exact expiry time the call fails, while one second before expiry a matching unused record remains valid. These boundaries use controlled trusted evaluation times. A real integration needs an authoritative time source. A timestamp freely supplied in the agent’s arguments must not be allowed to decide whether its own approval is still valid.
Complete approval consumption and the database effect atomically
Publication begins an immediate write transaction. Inside it, the current draft and its approval are checked again. Only then is the record marked used and the draft marked published. Both changes commit together. The effect concerns only the flag in the original demonstration database; there is no real public article, external mail delivery or remote system mutation.
A controlled database trigger deliberately fails the publication-flag update. The approval consumption written just beforehand is rolled back as well. The draft remains unpublished. After removing that explicit fault trigger, the same approval can be used successfully. These conditions investigate the shared failure boundary at the actual database state rather than simulating rollback with a Boolean in the test runner.
An external publishing service would have a different completion boundary. Its effect cannot automatically participate in the same SQLite transaction. Such an integration needs its own work receipts, retry policy and handling of ambiguous responses. The small local state transition is therefore not described as a general exactly-once guarantee for remote systems. Its useful promise is narrower and demonstrable.
Concurrent calls must not perform one approval twice
Two actual database connections wait at a shared start barrier and attempt the same publication. One marks the draft and consumes the approval. The other encounters the already published state and is rejected. The saved result contains one published draft and one consumed record. Separate connections perform the operations, rather than two sequential decisions over a single in-memory object.
A later replay returns an error under this contract instead of returning the original success again. That distinguishes an approval boundary from a complete idempotent result service. A caller that loses its response would need a separate authorized status path to recover the outcome reliably. The article does not silently claim that additional function. Rejection of a duplicate effect and recovery of an earlier result are related but different behaviors.
The edit tool also rejects modification of an already published draft. A different editorial workflow might create a revised draft with new review. The required transitions belong to the actual product process. Our contract remains intentionally small so each permitted and rejected effect can be traced through the executed cases. Expanding the workflow means deliberately expanding its tests and authority model.
Document observations without invented model performance
The saved report includes each condition’s actual outcome together with Python and SQLite versions. Its examples identify the approval request, permitted effect and both competing scenarios. The explanatory illustration is assembled from these results. It contains no claimed AI success rate and no fabricated model comparison. All proposed tool messages were constructed under controlled conditions for the investigation.
Real agent operation also requires appropriate logging. Relevant decisions should be traceable without unnecessarily copying confidential content or usable approval identifiers. A log does not replace authorization, and a permission failure should not merely emit a warning while continuing the effect. The displayed core ends that path with a rejection. Observability should describe the decision that actually governed execution.
The report does not establish permanent security against arbitrary attacks. It establishes named deterministic properties and the counterexamples exercised for them. Model quality, complete authentication, operating-system isolation and external publication remain separate tasks. This division also helps maintenance: a prompt edit must not become an undocumented substitute for changing the actual permission boundary.

Use the 55 conditions as a concrete reviewed boundary
The following outcomes connect permitted calls with explicitly investigated denials. They show that a foreign source instruction alone creates no publication, that an approval request creates no record and that changed content makes the existing record unsuitable. Other cases cover message shape, byte limits, actor scope and persistent quota. Parallel execution and injected failure additionally investigate the shared database state.
Acceptance needs more than a large case count. It identifies the desired effect, the relevant boundary and evidence for both. Adding a network tool or allowing one approval to cover several drafts changes the contract. Existing cases remain useful starting points but do not automatically cover the newly granted capability. Scope should expand deliberately rather than through an innocent-looking optional parameter.
The complete core follows as one Python file using the standard library. Initialize creates its schema once. A trusted application path supplies context and the proposed message to dispatch. The separate approval function stays outside the agent directory. The resulting decision is small enough to review concretely and extend deliberately for the requirements of a real product, while keeping its unresolved integration assumptions visible.
Complete Python tool core
import hashlib
import json
import sqlite3
import uuid
class Denied(Exception):
pass
def unique_object(pairs):
result = {}
for key, value in pairs:
if key in result:
raise Denied("duplicate_property")
result[key] = value
return result
def parse_call(raw):
if not isinstance(raw, bytes) or len(raw) > 8192:
raise Denied("request_size")
try:
call = json.loads(raw.decode("utf-8"), object_pairs_hook=unique_object,
parse_constant=lambda value: (_ for _ in ()).throw(Denied("constant")))
except (ValueError, UnicodeError, RecursionError) as error:
raise Denied("invalid_json") from error
if type(call) is not dict or set(call) != {"tool", "args"}:
raise Denied("call_shape")
if type(call["tool"]) is not str or type(call["args"]) is not dict:
raise Denied("call_types")
return call
def connect(path):
db = sqlite3.connect(path, timeout=5, isolation_level=None)
db.row_factory = sqlite3.Row
db.execute("PRAGMA foreign_keys=ON")
return db
def initialize(db):
db.executescript("""
CREATE TABLE drafts(id TEXT PRIMARY KEY, actor TEXT NOT NULL,
body TEXT NOT NULL, published INTEGER NOT NULL DEFAULT 0);
CREATE TABLE approvals(id TEXT PRIMARY KEY, actor TEXT NOT NULL,
draft TEXT NOT NULL REFERENCES drafts(id), digest TEXT NOT NULL,
expires INTEGER NOT NULL, used INTEGER NOT NULL DEFAULT 0);
""")
def digest(body):
return hashlib.sha256(body.encode("utf-8")).hexdigest()
def exact(args, keys):
if set(args) != set(keys):
raise Denied("arguments")
def text(value, maximum):
if type(value) is not str or not value.strip() or len(value.encode("utf-8")) > maximum:
raise Denied("text")
return value
def owned(db, actor, draft):
text(draft, 64)
row = db.execute("SELECT * FROM drafts WHERE id=? AND actor=?", (draft, actor)).fetchone()
if row is None:
raise Denied("draft_scope")
return row
def issue_approval(db, actor, draft, now):
# Trusted separate operator path. Never exposed as an agent tool.
row = owned(db, actor, draft)
if row["published"]:
raise Denied("already_published")
token = str(uuid.uuid4())
db.execute("INSERT INTO approvals(id,actor,draft,digest,expires) VALUES(?,?,?,?,?)",
(token, actor, draft, digest(row["body"]), now + 300))
return token
def dispatch(db, actor, raw, now, sources):
# actor, sources and now come from trusted application context, not JSON.
if actor not in {"redaktion-a", "redaktion-b"} or type(now) is not int:
raise Denied("context")
call = parse_call(raw)
tool, args = call["tool"], call["args"]
if tool not in {"read_source", "create_draft", "edit_draft", "request_publication", "publish_draft"}:
raise Denied("tool")
if tool == "read_source":
exact(args, {"source"})
source = text(args["source"], 64)
if source not in sources.get(actor, {}):
raise Denied("source_scope")
return {"state": "untrusted_source", "body": sources[actor][source]}
db.execute("BEGIN IMMEDIATE")
try:
if tool == "create_draft":
exact(args, {"body"})
body = text(args["body"], 4096)
if db.execute("SELECT COUNT(*) FROM drafts WHERE actor=?", (actor,)).fetchone()[0] >= 3:
raise Denied("draft_quota")
draft = str(uuid.uuid4())
db.execute("INSERT INTO drafts(id,actor,body) VALUES(?,?,?)", (draft, actor, body))
result = {"state": "draft_created", "draft": draft}
else:
keys = {"draft", "body"} if tool == "edit_draft" else {"draft", "approval"} if tool == "publish_draft" else {"draft"}
exact(args, keys)
row = owned(db, actor, args["draft"])
if row["published"]:
raise Denied("already_published")
if tool == "edit_draft":
body = text(args["body"], 4096)
db.execute("UPDATE drafts SET body=? WHERE id=?", (body, row["id"]))
result = {"state": "draft_edited", "draft": row["id"]}
elif tool == "request_publication":
result = {"state": "requires_approval", "draft": row["id"], "digest": digest(row["body"])}
else:
token = text(args["approval"], 64)
approval = db.execute("SELECT * FROM approvals WHERE id=? AND actor=? AND draft=?",
(token, actor, row["id"])).fetchone()
if approval is None or approval["used"] or now >= approval["expires"]:
raise Denied("approval_scope_or_expiry")
if approval["digest"] != digest(row["body"]):
raise Denied("approval_content_changed")
db.execute("UPDATE approvals SET used=1 WHERE id=?", (token,))
db.execute("UPDATE drafts SET published=1 WHERE id=?", (row["id"],))
result = {"state": "published_in_demo_database", "draft": row["id"]}
db.execute("COMMIT")
return result
except BaseException:
db.execute("ROLLBACK")
raise
Authority and observed outcomes
| Operation | Actual outcome |
|---|---|
| Read allowed source with instruction-like content | Literal data, no write effect |
| Request publication | requires_approval without an issued record |
| Invent approval or move it to another draft | Rejected |
| Change content after approval | Existing record no longer matches |
| Execute at exact expiry | Rejected |
| Use matching current approval | Only demo flag set and approval consumed |
| Two connections attempt one effect | One success, one denial |
| Fail effect write after consuming approval | Both database changes rolled back |
Scoped agent-tool checklist
- Describe necessary tools and actual effects individually.
- Obtain actor and time from authoritative context.
- Validate every call against narrow shape and size limits.
- Do not let source text authorize additional tools.
- Enforce object scope and durable quotas at appropriate boundaries.
- Separate requesting approval from issuing it.
- Bind records to actor, object, content, time and consumption.
- Exercise concurrency and faults between write steps.
- Develop external effects, status recovery and runtime budgets separately.
- Do not infer model performance or OS isolation from these tests.
Primary sources and review scope
Sources reviewed on 9 November 2026. Original deterministic tool gateway with 55 executed Python/SQLite conditions, synchronized separate connections and an actual injected database failure. No model request, external publication, complete authentication or operating-system sandbox.








