val-town-http-mcp-serverapi.ts11 matches
1import {Config} from "./types.ts"
23export async function callValTownApi(
4config: Config,
5path: string,
7): Promise<any> {
8// Path conversion for endpoints that have changed in v2
9let apiPath = path
1011// If any old v1 paths are accidentally used, convert them to v2
12if (path.startsWith("/v1/projects")) {
13apiPath = path.replace("/v1/projects", "/v2/vals")
14console.warn(`Converting deprecated v1 path to v2: ${path} → ${apiPath}`)
15} else if (path.startsWith("/v1/alias/projects")) {
16apiPath = path.replace("/v1/alias/projects", "/v2/alias/vals")
17console.warn(`Converting deprecated v1 path to v2: ${path} → ${apiPath}`)
18}
1920const url = `${config.apiBase}${apiPath}`
2122if (!config.apiToken) {
23throw new Error("API token is required for ValTown API calls");
24}
2526const headers: HeadersInit = {
27'Authorization': `Bearer ${config.apiToken}`,
28'Content-Type': 'application/json',
29}
39if (!response.ok) {
40const errorText = await response.text()
41throw new Error(`API error (${response.status}): ${errorText}`)
42}
43
twilioWebhookmain.tsx3 matches
52});
5354// Send the SMS via Twilio API
55const twilioResponse = await fetch(
56`https://api.twilio.com/2010-04-01/Accounts/${sid}/Messages.json`,
57{
58method: "POST",
67if (!twilioResponse.ok) {
68const errorText = await twilioResponse.text();
69console.error("Twilio API error:", twilioResponse.status, errorText);
70return new Response(`Twilio error: ${errorText}`, { status: 500 });
71}
sqliteExplorerAppmain.tsx2 matches
27<head>
28<title>SQLite Explorer</title>
29<link rel="preconnect" href="https://fonts.googleapis.com" />
3031<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin />
32<link
33href="https://fonts.googleapis.com/css2?family=Fira+Code:wght@300..700&family=Source+Sans+3:ital,wght@0,200..900;1,200..900&display=swap"
34rel="stylesheet"
35/>
sqliteExplorerAppREADME.md1 match
13## Authentication
1415Login to your SQLite Explorer with [password authentication](https://www.val.town/v/pomdtr/password_auth) with your [Val Town API Token](https://www.val.town/settings/api) as the password.
1617## Todos / Plans
sqlite_adminREADME.md1 match
9To use it on your own Val Town SQLite database, [fork it](https://www.val.town/v/stevekrouse/sqlite_admin/fork) to your account.
1011It uses [basic authentication](https://www.val.town/v/pomdtr/basicAuth) with your [Val Town API Token](https://www.val.town/settings/api) as the password (leave the username field blank).
1213Migrated from folder: utils/sqlite_admin/sqlite_admin
tanstackReactHonoExampleindex.ts3 matches
18app.get("/shared/**/*", (c) => serveFile(c.req.path, import.meta.url));
1920// API endpoints
21app.get("/api/messages", async (c) => {
22const messages = await getMessages();
23return c.json(messages);
24});
2526app.post("/api/messages", async (c) => {
27const { content } = await c.req.json();
28
tanstackReactHonoExampleREADME.md3 matches
38```
3940## API Endpoints
4142- `GET /` - Serves the React application with initial data
43- `GET /api/messages` - Fetch all messages (JSON)
44- `POST /api/messages` - Create a new message
45- `GET /public/**` - Static assets (CSS, JS, etc.)
46- `/*` - All other routes handled by TanStack Router
tanstackReactHonoExampleREADME.md5 matches
8## Hono
910This app uses [Hono](https://hono.dev/) as the API framework. You can think of Hono as a replacement for [ExpressJS](https://expressjs.com/) that works in serverless environments like Val Town or Cloudflare Workers. If you come from Python or Ruby, Hono is also a lot like [Flask](https://github.com/pallets/flask) or [Sinatra](https://github.com/sinatra/sinatra), respectively.
1112## Serving assets to the frontend
20### `index.html`
2122The most complicated part of this backend API is serving index.html. In this app (like most apps) we serve it at the root, ie `GET /`.
2324We *bootstrap* `index.html` with some initial data from the server, so that it gets dynamically injected JSON data without having to make another round-trip request to the server to get that data on the frontend. This is a common pattern for client-side rendered apps.
2526## CRUD API Routes
2728This app has two CRUD API routes: for reading and inserting into the messages table. They both speak JSON, which is standard. They import their functions from `/backend/database/queries.ts`. These routes are called from the React app to refresh and update data.
2930## Errors
3132Hono and other API frameworks have a habit of swallowing up Errors. We turn off this default behavior by re-throwing errors, because we think most of the time you'll want to see the full stack trace instead of merely "Internal Server Error". You can customize how you want errors to appear.
tanstackReactHonoExamplequeries.ts2 matches
7queryKey: ["messages"],
8queryFn: async () => {
9const response = await fetch("/api/messages");
10if (!response.ok) {
11throw new Error("Failed to fetch messages");
25return useMutation({
26mutationFn: async (content: string) => {
27const response = await fetch("/api/messages", {
28method: "POST",
29headers: { "Content-Type": "application/json" },
ChatHTMLRenderer.tsx23 matches
9}
1011interface MCPContextAPI {
12// Tool operations
13listTools: () => Promise<any[]>;
37* - Renders HTML in a secure iframe
38* - Provides fullscreen enter/exit affordances
39* - Exposes MCP context API to iframe content
40* - Handles iframe communication via postMessage
41*/
46const [isLoading, setIsLoading] = useState(true);
4748// Create MCP context API that will be exposed to iframe
49const createMCPContext = useCallback((): MCPContextAPI => {
50const findClientByName = (serverName: string) => {
51console.log("[MCP/Browser Renderer] Finding client by name:", serverName, mcpClients);
210const { type, id, method, args } = event.data;
211212if (type !== "mcp-api-call") {
213return;
214}
219220if (typeof methodFunc !== "function") {
221throw new Error(`Unknown MCP API method: ${method}`);
222}
223225226iframe.contentWindow?.postMessage({
227type: "mcp-api-response",
228id,
229success: true,
232} catch (error) {
233iframe.contentWindow?.postMessage({
234type: "mcp-api-response",
235id,
236success: false,
252</script>
253<script>
254// MCP Context API for iframe content
255window.mcpContext = {
256// Async wrapper for postMessage communication
257async callAPI(method, ...args) {
258return new Promise((resolve, reject) => {
259const id = Math.random().toString(36).substr(2, 9);
260
261const handleResponse = (event) => {
262if (event.data.type === 'mcp-api-response' && event.data.id === id) {
263window.removeEventListener('message', handleResponse);
264if (event.data.success) {
273
274window.parent.postMessage({
275type: 'mcp-api-call',
276id,
277method,
282setTimeout(() => {
283window.removeEventListener('message', handleResponse);
284reject(new Error('MCP API call timeout'));
285}, 30000);
286});
288
289// Convenience methods
290async listTools() { return this.callAPI('listTools'); },
291async callTool(serverName, toolName, args) { return this.callAPI('callTool', serverName, toolName, args); },
292async listPrompts() { return this.callAPI('listPrompts'); },
293async getPrompt(serverName, promptName, args) { return this.callAPI('getPrompt', serverName, promptName, args); },
294async listResources() { return this.callAPI('listResources'); },
295async readResource(serverName, uri) { return this.callAPI('readResource', serverName, uri); },
296log(level, message, data) { this.callAPI('log', level, message, data); },
297requestFullscreen() { this.callAPI('requestFullscreen'); },
298exitFullscreen() { this.callAPI('exitFullscreen'); },
299async isFullscreen() { return this.callAPI('isFullscreen'); }
300};
301