32<ol>
33<li>
34Login with your Val Town API token (with projects:read, projects:write, user:read permissions)
35</li>
36<li>Select a project to work on</li>
70</div>
71<h3>Cost Tracking</h3>
72<p>See estimated API usage costs for each interaction</p>
73</div>
74</section>
79<ul>
80<li>React frontend with TypeScript</li>
81<li>Hono API server backend</li>
82<li>Web Audio API for sound notifications</li>
83<li>AI SDK for Claude integration</li>
84</ul>
85<p>
86The application proxies requests to the Anthropic API and Val Town API, allowing Claude to view and edit your
87project files directly.
88</p>
Townie.cursorrules10 matches
13- Generate code in TypeScript or TSX
14- Add appropriate TypeScript types and interfaces for all data structures
15- Prefer official SDKs or libraries than writing API calls directly
16- Ask the user to supply API or library documentation if you are at all unsure about it
17- **Never bake in secrets into the code** - always use environment variables
18- Include comments explaining complex logic (avoid commenting obvious operations)
23### 1. HTTP Trigger
2425- Create web APIs and endpoints
26- Handle HTTP requests and responses
27- Example structure:
173However, it's *extremely importing* to note that `parseProject` and other Standard Library utilities ONLY RUN ON THE SERVER.
174If you need access to this data on the client, run it in the server and pass it to the client by splicing it into the HTML page
175or by making an API request for it.
176177## Val Town Platform Specifics
181- **AI Image:** To inline generate an AI image use: `<img src="https://maxm-imggenurl.web.val.run/the-description-of-your-image" />`
182- **Storage:** DO NOT use the Deno KV module for storage
183- **Browser APIs:** DO NOT use the `alert()`, `prompt()`, or `confirm()` methods
184- **Weather Data:** Use open-meteo for weather data (doesn't require API keys) unless otherwise specified
185- **View Source:** Add a view source link by importing & using `import.meta.url.replace("ems.sh", "val.town)"` (or passing this data to the client) and include `target="_top"` attribute
186- **Error Debugging:** Add `<script src="https://esm.town/v/std/catch"></script>` to HTML to capture client-side errors
187- **Error Handling:** Only use try...catch when there's a clear local resolution; Avoid catches that merely log or return 500s. Let errors bubble up with full context
188- **Environment Variables:** Use `Deno.env.get('keyname')` when you need to, but generally prefer APIs that don't require keys
189- **Imports:** Use `https://esm.sh` for npm and Deno dependencies to ensure compatibility on server and browser
190- **Storage Strategy:** Only use backend storage if explicitly required; prefer simple static client-side sites
224### Backend (Hono) Best Practices
225226- Hono is the recommended API framework
227- Main entry point should be `backend/index.ts`
228- **Static asset serving:** Use the utility functions to read and serve project files:
248});
249```
250- Create RESTful API routes for CRUD operations
251- Always include this snippet at the top-level Hono app to re-throwing errors to see full stack traces:
252```ts
285- For files in the project, use `readFile` helpers
2862875. **API Design:**
288- `fetch` handler is the entry point for HTTP vals
289- Run the Hono app with `export default app.fetch // This is the entry point for HTTP vals`
1# Anthropic Streaming Chat with MCP
23A mobile-optimized single page chat application that uses the Anthropic Messages API with **real-time streaming** and MCP (Model Context Protocol) server support.
45Source: https://www.val.town/x/c15r/Chat
16- **⏹️ Stream control** - Stop streaming at any time with the stop button
17- Full-screen mobile-optimized chat interface
18- Direct client-side Anthropic API integration with server-side streaming proxy
19- **Model selection** - Choose between different Claude models (3.5 Sonnet, 3.5 Haiku, 3 Opus, etc.) without clearing chat history
20- Configurable MCP servers with localStorage persistence
6465The app stores configuration and chat history in localStorage:
66- `anthropic_api_key`: Your Anthropic API key
67- `selected_model`: The chosen Claude model (defaults to claude-3-5-sonnet-20241022)
68- `mcp_servers`: Array of configured MCP servers
69- `chat_messages`: Complete chat history (persists between page loads)
7071## API Endpoints
7273- `GET /` - Main application (serves frontend)
80811. Open the app at the provided URL
822. Click "Settings" in the footer to configure your Anthropic API key and select your preferred Claude model
833. Add/remove/toggle MCP servers as needed
844. Use the "Test" button next to each MCP server to verify connectivity (shows ✅ for success, ❌ for errors)
107- **Auto-scroll**: Messages automatically scroll to bottom during streaming
108- **Auto-resize**: Input field grows with content
109- **Error Handling**: Clear error messages for API issues with stream recovery
110- **Loading States**: Visual feedback during API calls and streaming
111- **Structured Responses**: MCP tool use and results are displayed in organized, collapsible sections
112- **Clean Interface**: Maximized chat area with no header, footer contains all controls
ChatuseAnthropicStream.tsx7 matches
86/* Anthropic SDK instance – memoised so we don't recreate each render */
87const anthropic = React.useMemo(() => {
88if (!config.anthropicApiKey) return null;
89return new Anthropic({
90dangerouslyAllowBrowser: true,
91apiKey: config.anthropicApiKey,
92baseURL: "https://api.anthropic.com", // explicit so it works with CORS pre‑flights
93defaultHeaders: {
94"anthropic-version": "2023-06-01",
95// Allow calling the API directly from the browser – you accept the risk!
96"anthropic-dangerous-direct-browser-access": "true",
97},
98});
99}, [config.anthropicApiKey]);
100101/* Abort helper */
110const send = React.useCallback(
111async (history: Message[], userText: string): Promise<AssistantMsg> => {
112if (!anthropic) throw new Error("API key missing");
113if (status !== "idle") throw new Error("Stream already in progress");
114135})) as AsyncIterable<MessageStreamEvent>;
136} catch (err: any) {
137console.error("Failed to call Anthropic API", err);
138throw err;
139}
TownieuseUser.tsx1 match
1import { useState, useEffect } from "react";
23const USER_ENDPOINT = "/api/user";
45export function useUser() {
Townieuser-summary.ts1 match
20SUM(num_images) as total_images
21FROM ${USAGE_TABLE}
22WHERE our_api_token = 1
23GROUP BY user_id, username
24ORDER BY total_price DESC
TownieuseProject.tsx2 matches
1import { useState, useEffect } from "react";
23const PROJECT_ENDPOINT = "/api/project";
4const FILES_ENDPOINT = "/api/project-files";
56export function useProject(projectId: string, branchId?: string) {
TownieuseProjects.tsx1 match
1import { useState, useEffect } from "react";
23const ENDPOINT = "/api/projects-loader";
45export function useProjects() {
TownieuseCreateProject.tsx1 match
1import { useState, useEffect } from "react";
23const ENDPOINT = "/api/create-project";
45export function useCreateProject() {
TownieuseCreateBranch.tsx1 match
1import { useState, useEffect } from "react";
23const ENDPOINT = "/api/create-branch";
45export function useCreateBranch(projectId: string) {