Tin

Learn · Real programs · 30 of 34

Servers

Goal. Write a server where request input is untrusted, so injection does not compile.

A server is where untrusted input arrives. Every request body, query string and header was written by someone you don't know. Tin already treats a model's reply that way: it can't reach outside code until a person approves. A server treats the request the same way, so SQL injection, shell injection and open redirects are compile errors, not code review findings.

Routes

A server block lists its routes. Each one is a method, a path, the request and a body. A handler that returns a string answers 200 text/plain. tin serve runs it on localhost and reloads it when you save:

hello.tintin serve hello.tin
/// Says hello over HTTP.
server Api grants [net.listen(8080)] {
  get "/" (req) => "hello from Tin"
  get "/hello/:name" (req) => "hi {req.params.getOr("name", "")}"
  post "/echo" (req) => "you sent {req.body.len} bytes"
}
GET /
→ 200
hello from Tin

GET /hello/ada
→ 200
hi ada

POST /echo 'four'
→ 200
you sent 4 bytes

GET /nope
→ 404
{
  "error": "nothing at GET /nope"
}

DELETE /
→ 405
{
  "error": "DELETE is not allowed on /"
}

The output shows each request sent to the server and its answer. Paths and methods that match no route get a 404 or a 405 as JSON.

:name in a path is a parameter, read from req.params. The request also has method, path, query, headers (names in lowercase) and body.

Answering with types

Any other return type is sent as JSON, encoded the way tool results are. A Result answers Ok with 200 and Err with 400 and {"error"}. Return a Response to choose the status and headers yourself:

types.tintin serve types.tin
type Order = { id: int, item: string }

server Shop grants [net.listen(8080)] {
  get "/orders/:id" (req): Result<Order, string> {
    match parseInt(req.params.getOr("id", "")) {
      Some(id) => Ok(Order { id: id, item: "teapot" }),
      None => Err("an order id is a number"),
    }
  }
  get "/old" (req) => Response { status: 301, headers: mapOf([("Location", "/orders/1")]), body: "" }
}
GET /orders/7
→ 200
{
  "id": 7,
  "item": "teapot"
}

GET /orders/seven
→ 400
{
  "error": "an order id is a number"
}

GET /old
→ 301 location: /orders/1

Each request runs in a fresh instance of the program, like PHP: nothing in Tin memory outlives a request, and a panic fails only that request (500). Many requests run at once; each one waits only at a model call, a fetch or a sleep.

Injection doesn't compile

Here a query value goes into SQL. In most languages this runs, and ?name=x' OR 1=1-- reads the whole table. In Tin it doesn't build:

injection.tintin check injection.tin
import js "./db.mjs" {
  extern fn query(sql: string): string
}

server Api grants [net.listen(8080), js] {
  get "/users" (req) => query("select * from users where name = '{req.query.getOr("name", "")}'")
}
error: in GET /users: the request's input reaches extern fn query
 --> injection.tin:6:3
  |
6 |   get "/users" (req) => query("select * from users where name = '{req.query.getOr("name", "")}'")
  |   ^^^^^^^^^^^^
  = note: everything in the request (path params, query, headers, body) comes from the client
  = note: parse it to a number or bool first, match it against values the program writes itself, or put the call in a `guarded tool fn` behind `approve` (escapeHtml and encodeUri do not clean text for an extern: they protect HTML and URLs, not SQL or a shell)
  = note: this is how injection (SQL, shell, URL) is stopped at compile time

The compiler follows the request through variables, functions, arrays, maps and loops. An escaping function doesn't help unless it was made for that place: escapeHtml protects HTML, not SQL or a shell, so this is still an error:

parsed.tintin check parsed.tin
import js "./db.mjs" {
  extern fn query(sql: string): string
}

server Api grants [net.listen(8080), js] {
  get "/users" (req) => query("select * from users where name = '{escapeHtml(req.query.getOr("name", ""))}'")
}
error: in GET /users: the request's input reaches extern fn query
 --> parsed.tin:6:3
  |
6 |   get "/users" (req) => query("select * from users where name = '{escapeHtml(req.query.getOr("name", ""))}'")
  |   ^^^^^^^^^^^^
  = note: everything in the request (path params, query, headers, body) comes from the client
  = note: parse it to a number or bool first, match it against values the program writes itself, or put the call in a `guarded tool fn` behind `approve` (escapeHtml and encodeUri do not clean text for an extern: they protect HTML and URLs, not SQL or a shell)
  = note: this is how injection (SQL, shell, URL) is stopped at compile time
Where request input goesWhat makes it allowed
an extern fn (SQL, a shell, any JavaScript, Python or MCP)parse it to a number (parseInt, parseFloat), match it against your own values, or a guarded tool fn behind approve
the URL of a fetchthe same, or encodeUri for one part of the URL
a response headerthe same, or encodeUri (it stays a path: no scheme, no host, no line breaks)
the response bodyalways allowed: it goes back to the client who sent it

Headers count too. A redirect to wherever the query says is an open redirect, a favourite of phishing pages:

redirect.tintin check redirect.tin
server Api grants [net.listen(8080)] {
  get "/go" (req) => Response { status: 302, headers: mapOf([("Location", req.query.getOr("to", "/"))]), body: "" }
}
error: in GET /go: the request's input reaches a response header
 --> redirect.tin:2:3
  |
2 |   get "/go" (req) => Response { status: 302, headers: mapOf([("Location", req.query.getOr("to", "/"))]), body: "" }
  |   ^^^^^^^^^
  = note: everything in the request (path params, query, headers, body) comes from the client
  = note: a header from the client is an open redirect (Location) or a set cookie: write the header yourself, match the input against values the program writes, or encodeUri it to keep it a path
  = note: this is how injection (SQL, shell, URL) is stopped at compile time

Grants

grants [...] is the most the server may do: net.listen (with its default port; PORT wins), net.fetch, model, env, js, py, mcp, spawn. The compiler checks it against what the handlers and the agents they expose can reach. Forget one and the error says which, with a fix that adds it:

grants.tintin check grants.tin
/// Answers support questions.
agent Support { model: "mock" }

server Api grants [net.listen(8080)] {
  post "/ask" (req) => Support(req.body)
}
error: agent 'Support' (it has an endpoint) needs 'model', which server 'Api' does not grant
 --> grants.tin:2:1
  |
2 | agent Support { model: "mock" }
  | ^^^^^^^^^^^^^
  = note: call a model (agents and voice agents); or leave it out with `agents: [...]`
  = note: add it: `grants [net.listen(8080), model]`
  = fix: grant model

Every agent is an endpoint

A file with agents and no server is a server too. tin serve gives every agent POST /agents/<Name> (JSON, or Server-Sent Events with Accept: text/event-stream, a token at a time), a WebSocket at /agents/<Name>/ws that holds one conversation, and a tool on POST /mcp so other agents can call it:

agent.tintin serve agent.tin
/// Answers support questions.
agent Support { model: "mock" }
POST /agents/Support 'where is my order?'
→ 200
{
  "text": "mock: where is my order?",
  "turns": 1,
  "tokens": 27
}

GET /agents/Support
→ 200
{
  "name": "Support",
  "description": "Answers support questions.",
  "voice": false,
  "tools": [],
  "endpoints": {
    "http": "/agents/Support",
    "ws": "/agents/Support/ws",
    "mcp": "/mcp"
  }
}

In a server block, agents: [...] chooses which agents get endpoints, and ws "/voice" = Concierge connects a WebSocket to a voice agent: PCM audio from a browser's microphone in, the agent's speech out.

The same file deploys unchanged: tin deploy app.tin puts it at a name.tin.ad address, and --target cloudflare, vercel, cloudrun and the others build for those platforms. A target that can't do what the program needs (a WebSocket on Vercel) is a compile error. See Deploying.

Tasks

Task 1: Ask over HTTP

Give the Support agent its own route, POST /ask, that sends the request body as the question and answers with the reply. Hide the automatic /agents/Support endpoint.

Solution
task-1.solution.tintin serve task-1.solution.tin
/// Answers support questions.
agent Support { model: "mock" }

server Api grants [net.listen(8080), model] {
  agents: []
  post "/ask" (req) => Support(req.body)
}
POST /ask 'my teapot leaks'
→ 200
mock: my teapot leaks

POST /agents/Support 'hi'
→ 404
{
  "error": "no agent named Support"
}

The route calls a model, so the server needs model in its grants. agents: [] turns the automatic endpoints off.

Recap

  • Routes are declarations; answers are typed values.
  • Request input is tainted like model output until you parse or encode it.
  • net.listen is a grant, and every agent can be an endpoint.

In the reference: Servers · Request taint · Agent endpoints · Deploying