diff --git a/CHANGELOG.md b/CHANGELOG.md index 2e5563f..d90842c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,19 @@ # Changelog +## Unreleased + +### App + +- **Claude can attach and read files over MCP.** Four new tools: `list_attachments`, `add_attachment` (the content as text, or base64 for any other file), `get_attachment` (a text file comes back as its text, an image as an image Claude can look at, anything else as its name and download link) and `delete_attachment`. `get_card` lists a card's files. A file can be as large as the upload limit; it used to stop at 1 MB, before the upload limit was ever checked. +- **A broken upload is answered with "Expected a multipart/form-data body" (400)** instead of "Server Error" (500). + +### CLI + +- **`completo attachment TK-42` lists, adds, downloads and deletes a card's files.** `add` takes one or more files and checks that all of them are readable before uploading any; `download` saves under the file's own name, or where `-o` says (a directory, a path, or `-` for stdout), and refuses to overwrite without `--force`. Files are named by the 8-character ID the list prints or by their file name. `--json` works on every action. +- **`completo get` shows the real number of attachments.** It printed `attachments: 0` for every card. +- **A ticket ID with the wrong project key is refused** by every command, naming the card's real ticket. Card numbers are global, so `AB-42` used to act on card 42 in whatever project it belongs to. +- **An error is printed once, without the usage text.** A failed request printed the error, then every flag of the command, then the error again. A mistyped command or flag still shows the usage. + ## v0.19.2 ### App diff --git a/README.md b/README.md index f91de97..442fc34 100644 --- a/README.md +++ b/README.md @@ -209,7 +209,7 @@ claude mcp add --transport http completo https://completo.example.com/mcp \ --header "Authorization: Bearer " ``` -The tools mirror the CLI: list and search cards, read a card with its comments, create, update, move, assign and tag cards, comment, see your own tasks, and create a project. Every call runs with the permissions of whoever signed in or owns the token, exactly as the API does. +The tools mirror the CLI: list and search cards, read a card with its comments and attachments, create, update, move, assign and tag cards, comment, attach, read and delete files, see your own tasks, and create a project. `get_attachment` returns a text file as its text and an image as an image Claude can see. Every call runs with the permissions of whoever signed in or owns the token, exactly as the API does. ### The philosophy diff --git a/cli/cmd/attachment.go b/cli/cmd/attachment.go new file mode 100644 index 0000000..35ad8f4 --- /dev/null +++ b/cli/cmd/attachment.go @@ -0,0 +1,346 @@ +package cmd + +import ( + "encoding/json" + "errors" + "fmt" + "mime" + "os" + "path/filepath" + "strings" + + "github.com/scalecommerce-dev/completo/cli/internal" + "github.com/spf13/cobra" +) + +type attachment struct { + ID string `json:"id"` + CardID int `json:"cardId"` + OriginalName string `json:"originalName"` + MimeType string `json:"mimeType"` + Size int64 `json:"size"` + CreatedAt string `json:"createdAt"` + Uploader *struct { + Name string `json:"name"` + } `json:"uploader"` +} + +func (a *attachment) uploader() string { + if a.Uploader != nil && a.Uploader.Name != "" { + return a.Uploader.Name + } + // The schema keeps an attachment when its uploader is deleted (set null). + return "(deleted user)" +} + +// shortAttachmentID is how long an attachment ID prints, as for comments: a full +// UUID is longer than most file names, and resolveAttachmentRef takes any unique +// prefix, so what prints is directly usable as an argument. +const shortAttachmentID = 8 + +// resolveAttachmentRef finds the attachment a user named among one card's +// attachments: the full ID, an unambiguous ID prefix, or the exact file name when +// only one attachment has it. Resolving inside the card keeps a prefix from +// reaching a file on another card; `/api/attachments/:id` takes a bare UUID. +func resolveAttachmentRef(list []attachment, ref string) (*attachment, error) { + if ref == "" { + return nil, fmt.Errorf("attachment ID or file name required") + } + for i := range list { + if list[i].ID == ref { + return &list[i], nil + } + } + var byPrefix, byName []*attachment + for i := range list { + if strings.HasPrefix(list[i].ID, ref) { + byPrefix = append(byPrefix, &list[i]) + } + if list[i].OriginalName == ref { + byName = append(byName, &list[i]) + } + } + if len(byPrefix) == 1 { + return byPrefix[0], nil + } + if len(byName) == 1 { + return byName[0], nil + } + if len(byPrefix) > 1 || len(byName) > 1 { + matches := append(byPrefix, byName...) + ids := make([]string, 0, len(matches)) + for _, m := range matches { + ids = append(ids, m.ID+" "+m.OriginalName) + } + return nil, fmt.Errorf("%q matches more than one attachment: %s", ref, strings.Join(ids, ", ")) + } + return nil, fmt.Errorf("no attachment on this card matches %q", ref) +} + +// humanSize renders a byte count the way a file manager does. +func humanSize(n int64) string { + switch { + case n < 1024: + return fmt.Sprintf("%d B", n) + case n < 1024*1024: + return fmt.Sprintf("%.1f KB", float64(n)/1024) + default: + return fmt.Sprintf("%.1f MB", float64(n)/1024/1024) + } +} + +func formatAttachments(list []attachment) string { + if len(list) == 0 { + return "No attachments.\n" + } + rows := make([][]string, len(list)) + for i := range list { + a := &list[i] + id := a.ID + if len(id) > shortAttachmentID { + id = id[:shortAttachmentID] + } + rows[i] = []string{id, a.OriginalName, humanSize(a.Size), a.uploader(), internal.FormatTimestamp(a.CreatedAt)} + } + return internal.FormatTable([]string{"ID", "NAME", "SIZE", "UPLOADED BY", "CREATED"}, rows) +} + +func fetchAttachments(client *internal.Client, cardID int) ([]attachment, error) { + data, err := client.Get(fmt.Sprintf("/api/cards/%d/attachments", cardID)) + if err != nil { + return nil, fmt.Errorf("failed to fetch attachments: %w", err) + } + var list []attachment + if err := json.Unmarshal(data, &list); err != nil { + return nil, fmt.Errorf("failed to parse attachments: %w", err) + } + if list == nil { + list = []attachment{} + } + return list, nil +} + +// uploadContentType is the type the upload declares. The server's allowlist +// matches `image/*`, `text/*` and `application/pdf` on the declared type and +// everything else on the extension, so an image sent as octet-stream would be +// refused although its extension is fine. +func uploadContentType(name string) string { + if t := mime.TypeByExtension(strings.ToLower(filepath.Ext(name))); t != "" { + return t + } + return "application/octet-stream" +} + +// downloadTarget is where a download goes: the --output path, a file of the +// attachment's name inside --output when that is a directory, or the +// attachment's name in the current directory. The name is reduced to its base, +// so a stored name can never write outside the chosen directory. +func downloadTarget(output, originalName string) string { + name := filepath.Base(filepath.Clean("/" + strings.ReplaceAll(originalName, "\\", "/"))) + if name == "/" || name == "." || name == "" { + name = "attachment" + } + if output == "" { + return name + } + if info, err := os.Stat(output); err == nil && info.IsDir() { + return filepath.Join(output, name) + } + return output +} + +var ( + attachmentOutput string + attachmentForce bool +) + +var attachmentCmd = &cobra.Command{ + Use: "attachment [list|add|download|delete] [args...]", + Aliases: []string{"attachments"}, + Short: "Show or manage a card's attachments", + Long: `Show or manage a card's attachments. + +With no action, the card's attachments are listed. download and delete take an +attachment ID as printed by the list (any unambiguous prefix works) or the exact +file name. + + completo attachment TK-42 # list the card's files + completo attachment TK-42 add report.csv shot.png # attach one or more files + completo attachment TK-42 download 3f2a1b9c # save to ./ + completo attachment TK-42 download report.csv -o /tmp/ + completo attachment TK-42 download report.csv -o - # write to stdout + completo attachment TK-42 delete 3f2a1b9c + +The server decides which types and sizes it accepts (by default images, PDF, +text, Markdown, CSV, JSON, XML, zip and Office documents, up to 10 MB).`, + Args: cobra.MinimumNArgs(1), + RunE: func(cmd *cobra.Command, args []string) error { + client := mustClient() + + op := "list" + rest := []string{} + if len(args) > 1 { + op = args[1] + rest = args[2:] + } + switch op { + case "list", "add", "download", "delete": + default: + return fmt.Errorf("unknown action %q: expected add, download, delete or list", op) + } + + // Read every file before the first request: a typo in the third name should + // not leave the first two attached. + type upload struct { + name string + data []byte + } + var uploads []upload + if op == "add" { + if len(rest) == 0 { + return fmt.Errorf("file required: completo attachment %s add [file...]", args[0]) + } + for _, path := range rest { + data, err := os.ReadFile(path) + if err != nil { + return fmt.Errorf("failed to read %s: %w", path, err) + } + uploads = append(uploads, upload{name: filepath.Base(path), data: data}) + } + } + + c, err := fetchCard(client, args[0]) + if err != nil { + return err + } + + switch op { + case "list": + if len(rest) > 0 { + return fmt.Errorf("list takes no further arguments") + } + list, err := fetchAttachments(client, c.ID) + if err != nil { + return err + } + return printAttachments(list) + + case "add": + var added []attachment + for _, u := range uploads { + data, err := client.PostFile(fmt.Sprintf("/api/cards/%d/attachments", c.ID), "file", u.name, uploadContentType(u.name), u.data) + if err != nil { + // Report what already went up, so a retry does not attach it twice. + for _, a := range added { + fmt.Fprintf(os.Stderr, "Attached %s to %s.\n", a.OriginalName, c.ticket()) + } + return fmt.Errorf("failed to attach %s: %w", u.name, err) + } + var a attachment + if err := json.Unmarshal(data, &a); err != nil { + return fmt.Errorf("failed to parse upload response: %w", err) + } + added = append(added, a) + } + if jsonOutput { + return printJSON(added) + } + for _, a := range added { + fmt.Printf("Attached %s (%s) to %s.\n", a.OriginalName, humanSize(a.Size), c.ticket()) + } + list, err := fetchAttachments(client, c.ID) + if err != nil { + return err + } + fmt.Println() + fmt.Print(formatAttachments(list)) + return nil + + case "download": + if len(rest) != 1 { + return fmt.Errorf("download takes one attachment ID or file name") + } + list, err := fetchAttachments(client, c.ID) + if err != nil { + return err + } + target, err := resolveAttachmentRef(list, rest[0]) + if err != nil { + return err + } + path := fmt.Sprintf("/api/attachments/%s/download", target.ID) + if attachmentOutput == "-" { + _, err := client.Download(path, os.Stdout) + return err + } + dest := downloadTarget(attachmentOutput, target.OriginalName) + flags := os.O_WRONLY | os.O_CREATE | os.O_EXCL + if attachmentForce { + flags = os.O_WRONLY | os.O_CREATE | os.O_TRUNC + } + f, err := os.OpenFile(dest, flags, 0o644) + if errors.Is(err, os.ErrExist) { + return fmt.Errorf("%s already exists: pass --force to overwrite, or -o to choose another path", dest) + } + if err != nil { + return err + } + n, err := client.Download(path, f) + if cerr := f.Close(); err == nil { + err = cerr + } + if err != nil { + // A partial file looks like the real one; don't leave it behind. + os.Remove(dest) + return fmt.Errorf("failed to download %s: %w", target.OriginalName, err) + } + if jsonOutput { + return printJSON(map[string]any{"id": target.ID, "name": target.OriginalName, "path": dest, "size": n}) + } + fmt.Printf("Saved %s (%s) to %s.\n", target.OriginalName, humanSize(n), dest) + return nil + + case "delete": + if len(rest) != 1 { + return fmt.Errorf("delete takes one attachment ID or file name") + } + list, err := fetchAttachments(client, c.ID) + if err != nil { + return err + } + target, err := resolveAttachmentRef(list, rest[0]) + if err != nil { + return err + } + if _, err := client.Delete("/api/attachments/" + target.ID); err != nil { + return fmt.Errorf("failed to delete attachment: %w", err) + } + if jsonOutput { + return printJSON(map[string]any{"deleted": map[string]any{"id": target.ID, "name": target.OriginalName}}) + } + fmt.Printf("Deleted %s (%s) from %s.\n", target.OriginalName, target.ID, c.ticket()) + return nil + } + return fmt.Errorf("unknown action %q", op) + }, +} + +func printAttachments(list []attachment) error { + if jsonOutput { + return printJSON(list) + } + fmt.Print(formatAttachments(list)) + return nil +} + +func printJSON(v any) error { + enc := json.NewEncoder(os.Stdout) + enc.SetIndent("", " ") + return enc.Encode(v) +} + +func init() { + attachmentCmd.Flags().StringVarP(&attachmentOutput, "output", "o", "", "download: file or directory to save to, or - for stdout") + attachmentCmd.Flags().BoolVar(&attachmentForce, "force", false, "download: overwrite an existing file") + rootCmd.AddCommand(attachmentCmd) +} diff --git a/cli/cmd/attachment_test.go b/cli/cmd/attachment_test.go new file mode 100644 index 0000000..f4f8c6a --- /dev/null +++ b/cli/cmd/attachment_test.go @@ -0,0 +1,105 @@ +package cmd + +import ( + "path/filepath" + "strings" + "testing" +) + +func attachmentFixtures() []attachment { + return []attachment{ + {ID: "3f2a1b9c-1111-4000-8000-000000000001", OriginalName: "report.csv", Size: 120}, + {ID: "3f2a1b9c-2222-4000-8000-000000000002", OriginalName: "shot.png", Size: 2048}, + {ID: "7c1d0e4f-3333-4000-8000-000000000003", OriginalName: "dup.txt", Size: 1}, + {ID: "8d2e1f50-4444-4000-8000-000000000004", OriginalName: "dup.txt", Size: 2}, + } +} + +func TestResolveAttachmentRef(t *testing.T) { + list := attachmentFixtures() + for ref, want := range map[string]string{ + "3f2a1b9c-2222-4000-8000-000000000002": "shot.png", + "7c1d": "dup.txt", + "report.csv": "report.csv", + } { + got, err := resolveAttachmentRef(list, ref) + if err != nil || got.OriginalName != want { + t.Errorf("%q: got %v, %v; want %s", ref, got, err, want) + } + } + for ref, msg := range map[string]string{ + "3f2a1b9c": "more than one", + "dup.txt": "more than one", + "nope": "no attachment", + "": "required", + } { + if _, err := resolveAttachmentRef(list, ref); err == nil || !strings.Contains(err.Error(), msg) { + t.Errorf("%q: got %v, want error containing %q", ref, err, msg) + } + } +} + +func TestDownloadTargetStaysInTheChosenDirectory(t *testing.T) { + dir := t.TempDir() + for name, want := range map[string]string{ + "report.csv": "report.csv", + "../../etc/passwd": "passwd", + `..\..\win.ini`: "win.ini", + "/abs/path/file.txt": "file.txt", + "..": "attachment", + } { + if got := downloadTarget("", name); got != want { + t.Errorf("cwd, %q: got %q, want %q", name, got, want) + } + if got := downloadTarget(dir, name); got != filepath.Join(dir, want) { + t.Errorf("dir, %q: got %q, want %q", name, got, filepath.Join(dir, want)) + } + } + file := filepath.Join(dir, "chosen.bin") + if got := downloadTarget(file, "report.csv"); got != file { + t.Errorf("explicit file: got %q, want %q", got, file) + } +} + +func TestUploadContentType(t *testing.T) { + // The server's allowlist matches image/*, text/* and PDF on the declared type, + // so these must not go out as octet-stream. + for name, prefix := range map[string]string{ + "shot.PNG": "image/png", + "notes.txt": "text/plain", + "doc.pdf": "application/pdf", + "blob.weird": "application/octet-stream", + } { + if got := uploadContentType(name); !strings.HasPrefix(got, prefix) { + t.Errorf("%s: got %q, want %q", name, got, prefix) + } + } +} + +func TestFormatAttachments(t *testing.T) { + if got := formatAttachments(nil); got != "No attachments.\n" { + t.Errorf("empty: %q", got) + } + out := formatAttachments(attachmentFixtures()[:2]) + for _, want := range []string{"3f2a1b9c report.csv", "120 B", "2.0 KB", "(deleted user)"} { + if !strings.Contains(out, want) { + t.Errorf("missing %q in:\n%s", want, out) + } + } + if strings.Contains(out, "3f2a1b9c-1111") { + t.Errorf("full id printed:\n%s", out) + } +} + +func TestCheckTicketKey(t *testing.T) { + c := &cardResponse{card: card{ID: 42}, Project: &projectInfo{Key: "TK"}} + for _, ref := range []string{"TK-42", "tk-42", "42"} { + if err := checkTicketKey(ref, c); err != nil { + t.Errorf("%s: %v", ref, err) + } + } + err := checkTicketKey("AB-42", c) + if err == nil || !strings.Contains(err.Error(), "TK-42") { + t.Errorf("AB-42: got %v, want a refusal naming TK-42", err) + } +} diff --git a/cli/cmd/get.go b/cli/cmd/get.go index 3307cff..3fb2633 100644 --- a/cli/cmd/get.go +++ b/cli/cmd/get.go @@ -89,9 +89,27 @@ func fetchCard(client *internal.Client, ref string) (*cardResponse, error) { if err := json.Unmarshal(data, &c); err != nil { return nil, fmt.Errorf("failed to parse card: %w", err) } + if err := checkTicketKey(ref, &c); err != nil { + return nil, err + } return &c, nil } +// checkTicketKey refuses a ref whose project key is not the card's. Card numbers +// are global and the server reads only the number, so "AB-42" fetched card 42 of +// whatever project it is in, and the next command wrote to it. The MCP tools +// refuse the same way (server/mcp/tools.ts, loadCard). +func checkTicketKey(ref string, c *cardResponse) error { + i := strings.LastIndex(ref, "-") + if i <= 0 || c.Project == nil || c.Project.Key == "" { + return nil + } + if key := ref[:i]; !strings.EqualFold(key, c.Project.Key) { + return fmt.Errorf("%s does not exist: card %d is %s. Check the ticket ID", ref, c.ID, c.ticket()) + } + return nil +} + // ticket renders the card's display reference, falling back to the bare numeric // ID when the response carried no project key. func (c *cardResponse) ticket() string { diff --git a/cli/cmd/root.go b/cli/cmd/root.go index a796488..e3b71fb 100644 --- a/cli/cmd/root.go +++ b/cli/cmd/root.go @@ -21,7 +21,14 @@ var rootCmd = &cobra.Command{ Use: "completo", Short: "CLI for Completo kanban board", Long: "Interact with your Completo instance from the command line or AI agents.", + // Errors are printed once, by Execute. Cobra's own copy came first, followed by + // the usage text and then Execute's copy, so a failed upload printed its error + // twice around a screen of flags. + SilenceErrors: true, PersistentPreRunE: func(cmd *cobra.Command, args []string) error { + // Past argument and flag parsing, an error is the command's, not a usage + // mistake, so the usage text would only bury it. + cmd.SilenceUsage = true // Skip config loading for config and version commands if cmd.Name() == "config" || cmd.Name() == "version" || cmd.Name() == "self-update" { return nil @@ -37,7 +44,7 @@ var rootCmd = &cobra.Command{ func Execute() { if err := rootCmd.Execute(); err != nil { - fmt.Fprintln(os.Stderr, err) + fmt.Fprintln(os.Stderr, "Error:", err) os.Exit(1) } } diff --git a/cli/internal/client.go b/cli/internal/client.go index 4b0b81e..4e27856 100644 --- a/cli/internal/client.go +++ b/cli/internal/client.go @@ -5,7 +5,9 @@ import ( "encoding/json" "fmt" "io" + "mime/multipart" "net/http" + "net/textproto" "strings" "time" ) @@ -43,6 +45,24 @@ func (e *APIError) Error() string { } func (c *Client) do(method, path string, body io.Reader) (*http.Response, error) { + contentType := "" + if body != nil { + contentType = "application/json" + } + return c.doWith(c.HTTPClient, method, path, body, contentType) +} + +// transferTimeout bounds an upload or a download. The 30-second default suits a +// JSON call; a 10 MB attachment on a slow link can take longer than that. +const transferTimeout = 10 * time.Minute + +func (c *Client) transferClient() *http.Client { + hc := *c.HTTPClient + hc.Timeout = transferTimeout + return &hc +} + +func (c *Client) doWith(hc *http.Client, method, path string, body io.Reader, contentType string) (*http.Response, error) { // Don't use url.JoinPath - it escapes query parameters u := c.BaseURL + path @@ -51,11 +71,11 @@ func (c *Client) do(method, path string, body io.Reader) (*http.Response, error) return nil, err } req.Header.Set("Authorization", "Bearer "+c.Token) - if body != nil { - req.Header.Set("Content-Type", "application/json") + if contentType != "" { + req.Header.Set("Content-Type", contentType) } - resp, err := c.HTTPClient.Do(req) + resp, err := hc.Do(req) if err != nil { return nil, fmt.Errorf("request failed: %w", err) } @@ -116,3 +136,53 @@ func jsonBody(payload any) (io.Reader, error) { } return bytes.NewReader(b), nil } + +// PostFile uploads data as the multipart field `field`, named filename, and +// returns the response body. The body is built in memory so the request carries +// a Content-Length: the server refuses an oversized upload from that header +// before reading it, which a chunked body would not allow. +func (c *Client) PostFile(path, field, filename, contentType string, data []byte) (json.RawMessage, error) { + var buf bytes.Buffer + w := multipart.NewWriter(&buf) + h := make(textproto.MIMEHeader) + h.Set("Content-Disposition", fmt.Sprintf(`form-data; name="%s"; filename="%s"`, escapeQuotes(field), escapeQuotes(filename))) + if contentType == "" { + contentType = "application/octet-stream" + } + h.Set("Content-Type", contentType) + part, err := w.CreatePart(h) + if err != nil { + return nil, err + } + if _, err := part.Write(data); err != nil { + return nil, err + } + if err := w.Close(); err != nil { + return nil, err + } + resp, err := c.doWith(c.transferClient(), "POST", path, bytes.NewReader(buf.Bytes()), w.FormDataContentType()) + if err != nil { + return nil, err + } + defer resp.Body.Close() + b, err := io.ReadAll(resp.Body) + if err != nil { + return nil, err + } + return json.RawMessage(b), nil +} + +// Download streams the response body of path into dst and returns the byte count. +func (c *Client) Download(path string, dst io.Writer) (int64, error) { + resp, err := c.doWith(c.transferClient(), "GET", path, nil, "") + if err != nil { + return 0, err + } + defer resp.Body.Close() + return io.Copy(dst, resp.Body) +} + +// escapeQuotes is mime/multipart's own escaping for a Content-Disposition value. +var quoteEscaper = strings.NewReplacer("\\", "\\\\", `"`, "\\\"") + +func escapeQuotes(s string) string { return quoteEscaper.Replace(s) } diff --git a/cli/internal/client_upload_test.go b/cli/internal/client_upload_test.go new file mode 100644 index 0000000..cf28889 --- /dev/null +++ b/cli/internal/client_upload_test.go @@ -0,0 +1,75 @@ +package internal + +import ( + "bytes" + "io" + "net/http" + "net/http/httptest" + "strings" + "testing" +) + +func TestPostFileSendsMultipartWithLength(t *testing.T) { + var gotLen int64 + var gotName, gotType, gotBody, gotAuth string + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + gotLen = r.ContentLength + gotAuth = r.Header.Get("Authorization") + f, h, err := r.FormFile("file") + if err != nil { + t.Errorf("FormFile: %v", err) + http.Error(w, "bad", 400) + return + } + b, _ := io.ReadAll(f) + gotName, gotType, gotBody = h.Filename, h.Header.Get("Content-Type"), string(b) + w.WriteHeader(201) + w.Write([]byte(`{"id":"a1"}`)) + })) + defer srv.Close() + c := &Client{BaseURL: srv.URL, Token: "dzo_x", HTTPClient: srv.Client()} + + res, err := c.PostFile("/api/cards/1/attachments", "file", `we"ird.csv`, "text/csv", []byte("a,b\n1,2\n")) + if err != nil { + t.Fatal(err) + } + if string(res) != `{"id":"a1"}` { + t.Errorf("response %s", res) + } + if gotLen <= 0 { + t.Errorf("no Content-Length: the server checks it before reading the body") + } + if gotAuth != "Bearer dzo_x" || gotName != `we"ird.csv` || gotType != "text/csv" || gotBody != "a,b\n1,2\n" { + t.Errorf("got auth=%q name=%q type=%q body=%q", gotAuth, gotName, gotType, gotBody) + } +} + +func TestPostFileAndDownloadReportServerErrors(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.WriteHeader(415) + w.Write([]byte(`{"message":"File type not allowed"}`)) + })) + defer srv.Close() + c := &Client{BaseURL: srv.URL, Token: "t", HTTPClient: srv.Client()} + + if _, err := c.PostFile("/x", "file", "a.exe", "", []byte("MZ")); err == nil || !strings.Contains(err.Error(), "File type not allowed") { + t.Errorf("upload: %v", err) + } + var buf bytes.Buffer + if _, err := c.Download("/x", &buf); err == nil || buf.Len() != 0 { + t.Errorf("download: err=%v, wrote %d bytes of an error page", err, buf.Len()) + } +} + +func TestDownloadStreamsTheBody(t *testing.T) { + srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + w.Write([]byte("payload")) + })) + defer srv.Close() + c := &Client{BaseURL: srv.URL, Token: "t", HTTPClient: srv.Client()} + var buf bytes.Buffer + n, err := c.Download("/f", &buf) + if err != nil || n != 7 || buf.String() != "payload" { + t.Errorf("n=%d err=%v body=%q", n, err, buf.String()) + } +} diff --git a/server/api/cards/[id].get.ts b/server/api/cards/[id].get.ts index a20c8b9..55fccb4 100644 --- a/server/api/cards/[id].get.ts +++ b/server/api/cards/[id].get.ts @@ -1,4 +1,4 @@ -import { eq } from 'drizzle-orm' +import { eq, sql } from 'drizzle-orm' export default defineEventHandler(async (event) => { const { user } = await resolveAuth(event) @@ -72,8 +72,15 @@ export default defineEventHandler(async (event) => { .from(schema.cards).where(eq(schema.cards.id, row.cards.parentId)).get() : undefined + // The CLI's `get` prints this, and printed 0 for every card while it was missing. + const attachmentCount = db.select({ count: sql`count(*)` }) + .from(schema.attachments) + .where(eq(schema.attachments.cardId, id)) + .get()?.count ?? 0 + return { ...row.cards, + attachmentCount, // The viewer's role in this project, as boards and lists already return, so the // client can show owner-only affordances (e.g. moderating others' comments). // Admins get a synthetic 'owner' — don't render it as a real project role. diff --git a/server/api/cards/[id]/attachments.post.ts b/server/api/cards/[id]/attachments.post.ts index dba2818..d1eb391 100644 --- a/server/api/cards/[id]/attachments.post.ts +++ b/server/api/cards/[id]/attachments.post.ts @@ -15,7 +15,14 @@ export default defineEventHandler(async (event) => { throw createError({ statusCode: 413, message: `File too large. Maximum size is ${UPLOAD_MAX_SIZE_MB}MB` }) } - const formData = await readFormData(event) + // A body that is not multipart (or is cut off) makes `readFormData` throw a + // TypeError, which reached the client as a 500. + let formData: FormData + try { + formData = await readFormData(event) + } catch { + throw createError({ statusCode: 400, message: 'Expected a multipart/form-data body with a "file" field' }) + } const file = formData.get('file') if (!file || !(file instanceof File)) { throw createError({ statusCode: 400, message: 'No file provided' }) diff --git a/server/assets/openapi.json b/server/assets/openapi.json index b492d9e..cfedd75 100644 --- a/server/assets/openapi.json +++ b/server/assets/openapi.json @@ -3033,6 +3033,10 @@ { "type": "object", "properties": { + "attachmentCount": { + "type": "integer", + "description": "Number of files attached to the card" + }, "assignee": { "$ref": "#/components/schemas/UserSummary" }, diff --git a/server/mcp/tools.ts b/server/mcp/tools.ts index 39d33d9..497169e 100644 --- a/server/mcp/tools.ts +++ b/server/mcp/tools.ts @@ -32,9 +32,27 @@ export interface ToolDefinition { /** A failure the model can act on: surfaced as an `isError` result, never as a protocol error. */ export class ToolError extends Error {} +/** + * A result that is more than JSON: `get_attachment` hands an image back as an + * image block the model can look at, and a text file as its text, rather than a + * base64 string inside a JSON document. `structured` is what `structuredContent` + * carries, so a client that reads that field still gets the metadata. + */ +export class ToolContent { + readonly content: JsonObject[] + readonly structured: JsonObject + constructor(content: JsonObject[], structured: JsonObject) { + this.content = content + this.structured = structured + } +} + export interface ToolContext { get(path: string, query?: JsonObject): Promise + /** `body` may be a `FormData`, which goes out as multipart (attachments) instead of JSON. */ send(method: 'POST' | 'PUT' | 'PATCH' | 'DELETE', path: string, body?: unknown): Promise + /** A response body as bytes, for an attachment download. */ + getBytes(path: string): Promise /** * Where links point: `APP_URL` when set, as in emails and the OAuth metadata, so * a card link is the address people use rather than whatever host or forwarded @@ -99,6 +117,14 @@ interface ApiCardDetail extends ApiCard { subtaskCards: Array<{ id: number, ticket: string, title: string, statusId: string, assignee: { name: string } | null }> } interface ApiComment { id: string, body: string, authorName: string | null, createdAt: string, updatedAt: string | null } +interface ApiAttachment { + id: string + cardId: number + originalName: string + size: number + createdAt: string + uploader: { name: string } | null +} interface ApiSearchHit { id: number title: string @@ -219,6 +245,7 @@ function cardView(ctx: ToolContext, card: ApiCard, project: ApiProjectRef, statu dueDate: card.dueDate ? card.dueDate.slice(0, 10) : null, tags: (card.tags ?? []).map(t => t.name), ...(card.commentCount !== undefined ? { comments: card.commentCount } : {}), + ...(card.attachmentCount ? { attachments: card.attachmentCount } : {}), // A parent is always in the same project, so its ticket is the card's key. ...(card.parentId ? { parent: `${project.key}-${card.parentId}` } : {}), ...(card.subtasks ? { subtaskProgress: card.subtasks } : {}), @@ -252,6 +279,80 @@ function commentView(c: ApiComment) { return { author: c.authorName, body: c.body, createdAt: c.createdAt, edited: !!c.updatedAt && c.updatedAt !== c.createdAt } } +// ─── Attachments ───────────────────────────────────────────────────────────── + +/** + * Text a get_attachment result carries by default. A 10 MB log in one tool result + * buries everything else in the model's context; maxChars raises it when the + * whole file is the point. + */ +const ATTACHMENT_TEXT_DEFAULT_CHARS = 100_000 +const ATTACHMENT_TEXT_MAX_CHARS = 2_000_000 + +/** + * Images get_attachment returns as an image block. Larger ones are refused by + * model clients anyway (Claude's limit is 5 MB per image), so they come back as + * metadata and a link instead of a payload the client throws away. + */ +const ATTACHMENT_IMAGE_MAX_BYTES = 5 * 1024 * 1024 + +/** Served types the model can read as text; everything else is binary to it. */ +function isTextType(contentType: string): boolean { + return contentType.startsWith('text/') || contentType === 'application/json' || contentType === 'application/xml' +} + +/** Image types a model client renders. SVG is text that executes, not an image block. */ +const MODEL_IMAGE_TYPES = new Set(['image/png', 'image/jpeg', 'image/gif', 'image/webp']) + +function attachmentView(ctx: ToolContext, a: ApiAttachment) { + return { + id: a.id, + name: a.originalName, + size: a.size, + type: serveContentType(a.originalName), + uploadedBy: a.uploader?.name ?? null, + createdAt: a.createdAt, + url: `${ctx.origin}/api/attachments/${a.id}/download` + } +} + +/** + * The attachment a ref names among one card's attachments: the id, a unique id + * prefix (the CLI prints eight characters), or the exact file name when only one + * attachment has it. Resolving inside the card keeps a guessed id from reaching + * another card's file; `/api/attachments/:id` takes a bare id with no card in it. + */ +function resolveAttachment(list: ApiAttachment[], ref: string, ticket: string): ApiAttachment { + const w = ref.trim() + const exact = list.find(a => a.id === w) + if (exact) return exact + const byPrefix = w.length >= 4 ? list.filter(a => a.id.startsWith(w)) : [] + if (byPrefix.length === 1) return byPrefix[0]! + const byName = list.filter(a => a.originalName === w) + if (byName.length === 1) return byName[0]! + const names = list.map(a => `${a.id.slice(0, 8)} ${a.originalName}`).join(', ') + if (byPrefix.length > 1 || byName.length > 1) { + throw new ToolError(`"${ref}" matches more than one attachment on ${ticket}: ${names}. Use the id.`) + } + throw new ToolError(`No attachment "${ref}" on ${ticket}. Attachments: ${names || 'none'}`) +} + +/** The file content add_attachment was given, as bytes: exactly one of text or base64. */ +function attachmentBytes(args: JsonObject): Uint8Array { + const text = args.text + const b64 = args.base64 + if (text !== undefined && b64 !== undefined) throw new ToolError('Give text or base64, not both') + if (typeof text === 'string') return new TextEncoder().encode(text) + if (typeof b64 === 'string') { + const clean = b64.replace(/\s+/g, '') + if (!/^[A-Za-z0-9+/]*={0,2}$/.test(clean) || clean.length % 4 !== 0) { + throw new ToolError('"base64" is not valid base64') + } + return new Uint8Array(Buffer.from(clean, 'base64')) + } + throw new ToolError('Give the file content as "text" (UTF-8) or "base64"') +} + function projectOf(card: ApiCardDetail): ApiProjectRef { if (!card.project) throw new ToolError('Card has no project') return card.project @@ -410,7 +511,7 @@ const TOOLS: Tool[] = [ }, { name: 'get_card', - description: `A card in full: description (Markdown; checklist items are \`- [ ]\` lines), status, assignee, tags, due date, link, its parent or sub-tasks, and its latest ${CARD_COMMENT_LIMIT} comments, oldest first. Comments are newer than the description and override it where they disagree. When commentCount is higher, list_comments has the rest. Does not mark the card as read.`, + description: `A card in full: description (Markdown; checklist items are \`- [ ]\` lines), status, assignee, tags, due date, link, its parent or sub-tasks, its attachments (names; get_attachment reads one), and its latest ${CARD_COMMENT_LIMIT} comments, oldest first. Comments are newer than the description and override it where they disagree. When commentCount is higher, list_comments has the rest. Does not mark the card as read.`, inputSchema: schema({ card: CARD_REF }, ['card']), annotations: { readOnlyHint: true }, run: async (ctx, args) => { @@ -418,8 +519,12 @@ const TOOLS: Tool[] = [ // Context for the model, not the person reading the card: markRead=false // keeps their unread dot, as `completo get` does. const comments = await ctx.get(`/api/cards/${card.id}/comments?markRead=false`) + const attachments = card.attachmentCount + ? await ctx.get(`/api/cards/${card.id}/attachments`) + : [] return { ...cardView(ctx, card, projectOf(card), card.statuses), + ...(attachments.length ? { attachments: attachments.map(a => attachmentView(ctx, a)) } : {}), ...(card.subtaskCards.length ? { subtasks: card.subtaskCards.map(c => ({ @@ -598,6 +703,95 @@ const TOOLS: Tool[] = [ return { author: comment.authorName, body: comment.body, createdAt: comment.createdAt } } }, + { + name: 'list_attachments', + description: 'The files attached to a card: id, name, size, type, who uploaded it and a download link. get_attachment reads one.', + inputSchema: schema({ card: CARD_REF }, ['card']), + annotations: { readOnlyHint: true }, + run: async (ctx, args) => { + const card = await loadCard(ctx, need(args, 'card')) + const list = await ctx.get(`/api/cards/${card.id}/attachments`) + return list.map(a => attachmentView(ctx, a)) + } + }, + { + name: 'add_attachment', + description: `Attach a file to a card. Pass the content as "text" for a text file (CSV, Markdown, JSON, a log) or as "base64" for anything else; the name decides the type, so give it the right extension. Allowed: images, PDF, text, .md, .csv, .json, .xml, .zip and Office documents, up to the server's upload limit (${UPLOAD_MAX_SIZE_MB} MB by default).`, + inputSchema: schema({ + card: CARD_REF, + filename: { type: 'string', description: 'File name with extension, e.g. report.csv.' }, + text: { type: 'string', description: 'The file content as UTF-8 text. Use this or base64.' }, + base64: { type: 'string', description: 'The file content, base64-encoded. Use this or text.' } + }, ['card', 'filename']), + run: async (ctx, args) => { + const card = await loadCard(ctx, need(args, 'card')) + const filename = need(args, 'filename').trim() + if (/[\\/]/.test(filename)) throw new ToolError('"filename" is a name, not a path') + const bytes = attachmentBytes(args) + const form = new FormData() + form.append('file', new Blob([bytes as BlobPart], { type: serveContentType(filename) }), filename) + const created = await ctx.send('POST', `/api/cards/${card.id}/attachments`, form) + return { ticket: `${projectOf(card).key}-${card.id}`, ...attachmentView(ctx, created) } + } + }, + { + name: 'get_attachment', + description: `Read a file attached to a card. A text file (CSV, Markdown, JSON, XML, a log) comes back as its text, the first ${ATTACHMENT_TEXT_DEFAULT_CHARS.toLocaleString('en')} characters unless maxChars asks for more; a PNG, JPEG, GIF or WebP image comes back as an image. Any other file comes back as its details and download link only.`, + inputSchema: schema({ + card: CARD_REF, + attachment: { type: 'string', description: 'The attachment id (or its first 8 characters) or its exact file name, as list_attachments shows.' }, + maxChars: { type: 'integer', minimum: 1, maximum: ATTACHMENT_TEXT_MAX_CHARS, description: `For a text file: how many characters to return. Default ${ATTACHMENT_TEXT_DEFAULT_CHARS}.` } + }, ['card', 'attachment']), + annotations: { readOnlyHint: true }, + run: async (ctx, args) => { + const card = await loadCard(ctx, need(args, 'card')) + const ticket = `${projectOf(card).key}-${card.id}` + const list = await ctx.get(`/api/cards/${card.id}/attachments`) + const a = resolveAttachment(list, need(args, 'attachment'), ticket) + const meta = { ticket, ...attachmentView(ctx, a) } + const type = meta.type + if (isTextType(type)) { + const text = new TextDecoder().decode(await ctx.getBytes(`/api/attachments/${a.id}/download`)) + const limit = typeof args.maxChars === 'number' + ? Math.min(Math.max(Math.floor(args.maxChars), 1), ATTACHMENT_TEXT_MAX_CHARS) + : ATTACHMENT_TEXT_DEFAULT_CHARS + const cut = text.length > limit + const structured = { ...meta, chars: text.length, ...(cut ? { truncated: true, returnedChars: limit } : {}) } + return new ToolContent([ + { type: 'text', text: JSON.stringify(structured, null, 2) }, + { type: 'text', text: cut ? text.slice(0, limit) : text } + ], structured) + } + if (MODEL_IMAGE_TYPES.has(type) && a.size <= ATTACHMENT_IMAGE_MAX_BYTES) { + const bytes = await ctx.getBytes(`/api/attachments/${a.id}/download`) + return new ToolContent([ + { type: 'text', text: JSON.stringify(meta, null, 2) }, + { type: 'image', data: Buffer.from(bytes).toString('base64'), mimeType: type } + ], meta) + } + const why = MODEL_IMAGE_TYPES.has(type) + ? `The image is larger than ${ATTACHMENT_IMAGE_MAX_BYTES / 1024 / 1024} MB, so it is not returned.` + : 'This file type is not returned as content.' + return { ...meta, note: `${why} Download it from url, or with \`completo attachment ${ticket} download ${a.id.slice(0, 8)}\`.` } + } + }, + { + name: 'delete_attachment', + description: 'Remove a file from a card. Cannot be undone.', + inputSchema: schema({ + card: CARD_REF, + attachment: { type: 'string', description: 'The attachment id (or its first 8 characters) or its exact file name, as list_attachments shows.' } + }, ['card', 'attachment']), + annotations: { destructiveHint: true }, + run: async (ctx, args) => { + const card = await loadCard(ctx, need(args, 'card')) + const ticket = `${projectOf(card).key}-${card.id}` + const list = await ctx.get(`/api/cards/${card.id}/attachments`) + const a = resolveAttachment(list, need(args, 'attachment'), ticket) + await ctx.send('DELETE', `/api/attachments/${a.id}`) + return { ticket, deleted: { id: a.id, name: a.originalName } } + } + }, { name: 'my_tasks', description: 'Every open card assigned to the caller, grouped by project.', @@ -693,13 +887,24 @@ export function toolContext(event: H3Event, userId: string): ToolContext { // Untyped on purpose: Nuxt's typed routes try to match a dynamic path against // every route in the app and the compiler gives up ("Excessive stack depth"). const fetch = event.$fetch as unknown as (path: string, init: Record) => Promise - const call = async (path: string, init: { method?: string, body?: unknown, query?: JsonObject }): Promise => { + const call = async (path: string, init: { method?: string, body?: unknown, query?: JsonObject, bytes?: boolean }): Promise => { + const headers: Record = { accept: init.bytes ? '*/*' : 'application/json' } + let body = init.body + if (body instanceof FormData) { + // The in-process fetch drops a FormData body's multipart Content-Type, and the + // upload handler then cannot parse it. Encoding it here keeps the boundary in + // the header the handler reads. + const encoded = new Response(body) + headers['content-type'] = encoded.headers.get('content-type')! + body = new Uint8Array(await encoded.arrayBuffer()) + } try { return await fetch(path, { method: init.method ?? 'GET', - body: init.body, + body, query: init.query, - headers: { accept: 'application/json' } + headers, + ...(init.bytes ? { responseType: 'arrayBuffer' } : {}) }) as T } catch (err) { throw new ToolError(apiMessage(err)) @@ -708,6 +913,7 @@ export function toolContext(event: H3Event, userId: string): ToolContext { return { get: (path, query) => call(path, { query }), send: (method, path, body) => call(path, { method, body }), + getBytes: path => call(path, { bytes: true }), origin: publicOrigin(event), userId } diff --git a/server/middleware/body-limit.ts b/server/middleware/body-limit.ts index 74802a0..ca73081 100644 --- a/server/middleware/body-limit.ts +++ b/server/middleware/body-limit.ts @@ -8,9 +8,16 @@ * declare their length (a chunked body has none, and would be buffered blind); * every other route gets a generous one. Uploads are exempt: they check their own * limit (`cards/[id]/attachments.post.ts`). + * + * `/mcp` carries an attachment as base64 inside JSON (`add_attachment`), which is + * a third larger than the file, so its limit is the upload limit in base64 plus + * room for the JSON-RPC envelope. At the default limit a 10 MB file would have + * been refused at 1 MB, before the tool or the upload handler could say why. */ const ANONYMOUS_MAX_BYTES = 16 * 1024 const DEFAULT_MAX_BYTES = 1024 * 1024 +const MCP_ENVELOPE_BYTES = 64 * 1024 +const MCP_MAX_BYTES = Math.max(DEFAULT_MAX_BYTES, Math.ceil(UPLOAD_MAX_SIZE_BYTES / 3) * 4 + MCP_ENVELOPE_BYTES) const BODY_METHODS = new Set(['POST', 'PUT', 'PATCH', 'DELETE']) function isAnonymousRoute(path: string): boolean { @@ -29,7 +36,7 @@ export default defineEventHandler((event) => { const lengthHeader = getRequestHeader(event, 'content-length') const declared = lengthHeader === undefined ? undefined : Number(lengthHeader) const anonymous = isAnonymousRoute(path) - const limit = anonymous ? ANONYMOUS_MAX_BYTES : DEFAULT_MAX_BYTES + const limit = anonymous ? ANONYMOUS_MAX_BYTES : path === '/mcp' ? MCP_MAX_BYTES : DEFAULT_MAX_BYTES if (declared === undefined) { if (anonymous && getRequestHeader(event, 'transfer-encoding')) { diff --git a/server/routes/mcp.post.ts b/server/routes/mcp.post.ts index 04dde5f..fd0082a 100644 --- a/server/routes/mcp.post.ts +++ b/server/routes/mcp.post.ts @@ -16,13 +16,13 @@ * * The tools live in `server/mcp/tools.ts`; this file only speaks the protocol. */ -import { ToolError, findTool, toolContext, toolDefinitions } from '../mcp/tools' +import { ToolContent, ToolError, findTool, toolContext, toolDefinitions } from '../mcp/tools' import type { JsonObject } from '../mcp/tools' /** Newest first. A client asking for one of these gets it back; anything else gets the newest. */ const PROTOCOL_VERSIONS = ['2025-11-25', '2025-06-18', '2025-03-26', '2024-11-05'] -const INSTRUCTIONS = `Completo is a kanban app. Cards live in a project and have a status; a card is named by its ticket id, e.g. TK-42 (project key, dash, number). Boards and lists are views over the same cards: you move cards between statuses, never between boards. Statuses and tags are per project; when a name is uncertain, call get_project first rather than guess, and prefer the exact name it returns. A card's workflow is typically Backlog, To Do, In Progress, Review, Done. Done cards older than the project's retention window disappear from lists; that is expected. Descriptions are Markdown; checklist items are "- [ ]" lines. A card can have sub-tasks: cards of the same project with a parent, one level deep. A card with open sub-tasks cannot move to the done status until they are done.` +const INSTRUCTIONS = `Completo is a kanban app. Cards live in a project and have a status; a card is named by its ticket id, e.g. TK-42 (project key, dash, number). Boards and lists are views over the same cards: you move cards between statuses, never between boards. Statuses and tags are per project; when a name is uncertain, call get_project first rather than guess, and prefer the exact name it returns. A card's workflow is typically Backlog, To Do, In Progress, Review, Done. Done cards older than the project's retention window disappear from lists; that is expected. Descriptions are Markdown; checklist items are "- [ ]" lines. A card can have sub-tasks: cards of the same project with a parent, one level deep. A card with open sub-tasks cannot move to the done status until they are done. Cards carry files: list_attachments shows them, get_attachment reads one (text as text, images as images), add_attachment attaches a file given as text or base64.` interface RpcRequest { jsonrpc?: string, id?: string | number | null, method?: string, params?: JsonObject } interface RpcResponse { jsonrpc: '2.0', id: string | number | null, result?: unknown, error?: { code: number, message: string, data?: unknown } } @@ -140,6 +140,9 @@ async function handle(message: unknown, ctx: ReturnType): Pr const args = (req.params?.arguments && typeof req.params.arguments === 'object' ? req.params.arguments : {}) as JsonObject try { const result = await tool.run(ctx, args) + if (result instanceof ToolContent) { + return reply(req.id, { content: result.content, structuredContent: result.structured, isError: false }) + } return reply(req.id, { content: [{ type: 'text', text: JSON.stringify(result, null, 2) }], structuredContent: Array.isArray(result) ? { items: result } : result, diff --git a/skills/completo/SKILL.md b/skills/completo/SKILL.md index c30c826..65b3888 100644 --- a/skills/completo/SKILL.md +++ b/skills/completo/SKILL.md @@ -241,6 +241,25 @@ Comments are the right place for a progress note, a link to a commit, or a quest prefer them over rewriting the description, which is the ticket's *specification* and should keep saying what the work is. +## Attaching files + +```bash +completo attachment TK-42 # list files, with IDs +completo attachment TK-42 add report.csv shot.png # attach one or more files +completo attachment TK-42 download 3f2a1b9c # save to ./ +completo attachment TK-42 download report.csv -o /tmp/ # into a directory (or a path, or - for stdout) +completo attachment TK-42 delete 3f2a1b9c +``` + +`download` and `delete` take the attachment ID as printed by the list (the 8-character form or any +unambiguous prefix) or the exact file name. `download` refuses to overwrite an existing file unless +you pass `--force`. `add` reads every file before it uploads any, so a typo in one name attaches +nothing. The server decides what it accepts: by default images, PDF, text, Markdown, CSV, JSON, +XML, zip and Office documents, up to 10 MB each; a refusal prints the server's reason. + +Attach data, logs or screenshots that back up a ticket instead of pasting them into the +description or a comment. + ## Creating projects ```bash @@ -271,6 +290,7 @@ Run `completo --help` for full, always-current flag lists. The essenti | `completo tags [project]` | List a project's tags (names are exact) | | `completo tag [add\|remove\|set] [tags...]` | Show or change a card's tags (no action lists them) | | `completo comment [add\|edit\|delete] [args...]` | Show or manage a card's comments (no action lists them) | +| `completo attachment [add\|download\|delete] [args...]` | Show or manage a card's files (no action lists them); `download -o `, `--force` to overwrite | | `completo my-tasks` | Cards assigned to you | | `completo search [--project slug]` | Search cards in the project from `.completo`, or the one named | | `completo project-create [flags]` | Create a project (see above) | @@ -278,14 +298,16 @@ Run `completo --help` for full, always-current flag lists. The essenti | `completo config` / `version` / `self-update` | Configure credentials / print version / update the CLI | Read commands (`get`, `list`, `next`, `search`, `my-tasks`, `statuses`, `projects`, `create`, -`project-create`, `briefing`, `tags`) accept `--json` for machine-readable output, as do `tag` and -`comment` — which print the card's resulting tag or comment list after every change, so a mutation -doubles as a read. `--env-file` overrides config on any command. +`project-create`, `briefing`, `tags`) accept `--json` for machine-readable output, as do `tag`, +`comment` and `attachment` — `tag` and `comment` print the card's resulting tag or comment list after +every change, so a mutation doubles as a read. `--env-file` overrides config on any command. ## Notes - `update` can only change title/description/priority/due/parent. Use `move` for status, `assign` - for assignee, `tag` for tags and `comment` for comments — not `update`. + for assignee, `tag` for tags, `comment` for comments and `attachment` for files — not `update`. +- A ticket ID whose project key does not match the card is refused (card numbers are global, so + `AB-42` would otherwise act on card 42 of another project). - `next`, `list`, `briefing`, `statuses` and `tags` take an optional positional project slug if you're not relying on `.completo`. - To scope work to a project without a `.completo` file, pass `--project` (on `create`) or the diff --git a/tests/integration/cards/attachments.test.ts b/tests/integration/cards/attachments.test.ts index 025c3b0..3cba890 100644 --- a/tests/integration/cards/attachments.test.ts +++ b/tests/integration/cards/attachments.test.ts @@ -98,6 +98,26 @@ describe('Card Attachments', async () => { expect(res.status).toBe(404) }) + it('counts a card\'s attachments on the card itself', async () => { + const card = await createTestCard(user, projectId, statusId, { title: 'Counted' }) + const before = await $fetch(`/api/cards/${card.id}`, { headers: user.headers }) as { attachmentCount: number } + expect(before.attachmentCount).toBe(0) + await uploadAttachment(user, card.id, { filename: 'a.txt', content: 'a' }) + await uploadAttachment(user, card.id, { filename: 'b.txt', content: 'b' }) + const after = await $fetch(`/api/cards/${card.id}`, { headers: user.headers }) as { attachmentCount: number } + expect(after.attachmentCount).toBe(2) + }) + + it('answers a body that is not multipart with 400, not a server error', async () => { + const res = await fetch(url(`/api/cards/${cardId}/attachments`), { + method: 'POST', + body: JSON.stringify({ file: 'x' }), + headers: { ...user.headers, 'content-type': 'application/json' } + }) + expect(res.status).toBe(400) + expect((await res.json() as { message: string }).message).toContain('multipart/form-data') + }) + it('rejects non-member on upload', async () => { const res = await fetch(url(`/api/cards/${cardId}/attachments`), { method: 'POST', diff --git a/tests/integration/mcp.test.ts b/tests/integration/mcp.test.ts index 551a775..430581d 100644 --- a/tests/integration/mcp.test.ts +++ b/tests/integration/mcp.test.ts @@ -102,7 +102,7 @@ describe('POST /mcp', () => { const res = await rpc(headers, 'tools/list') const tools = res.result?.tools as Array<{ name: string, inputSchema: { type: string, required?: string[] } }> const names = tools.map(t => t.name) - for (const expected of ['list_projects', 'get_project', 'list_cards', 'search_cards', 'get_card', 'create_card', 'update_card', 'move_card', 'assign_card', 'tag_card', 'list_comments', 'add_comment', 'my_tasks', 'create_project']) { + for (const expected of ['list_projects', 'get_project', 'list_cards', 'search_cards', 'get_card', 'create_card', 'update_card', 'move_card', 'assign_card', 'tag_card', 'list_comments', 'add_comment', 'list_attachments', 'add_attachment', 'get_attachment', 'delete_attachment', 'my_tasks', 'create_project']) { expect(names).toContain(expected) } const move = tools.find(t => t.name === 'move_card')! @@ -371,3 +371,108 @@ describe('POST /mcp', () => { }) }) }) + +describe('MCP attachments', () => { + let headers: Record + let ticket: string + + // A 1x1 transparent PNG. + const PNG_BASE64 = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mNkYPhfDwAChwGA60e6kgAAAABJRU5ErkJggg==' + + beforeAll(async () => { + const owner = await registerTestUser() + headers = (await createTestToken(owner)).headers + const project = await createTestProject(owner, { name: `MCP files ${Date.now()}` }) + ticket = (await call(headers, 'create_card', { project: project.slug, title: 'Has files' })).data.ticket + }) + + it('attaches a text file, lists it, reads it back as text and shows it on the card', async () => { + const csv = 'cluster,gap_gb\ncalumet,1.52\nbabyone,2.14\n' + const added = await call(headers, 'add_attachment', { card: ticket, filename: 'session_gap.csv', text: csv }) + expect(added.isError).toBe(false) + expect(added.data).toMatchObject({ ticket, name: 'session_gap.csv', size: csv.length, type: 'text/csv' }) + + const list = await call(headers, 'list_attachments', { card: ticket }) + expect(list.data.map((a: { name: string }) => a.name)).toContain('session_gap.csv') + + // By name, and by the 8-character id the CLI prints. + for (const ref of ['session_gap.csv', String(added.data.id).slice(0, 8)]) { + const got = await call(headers, 'get_attachment', { card: ticket, attachment: ref }) + expect(got.isError, ref).toBe(false) + expect(got.content[1]).toEqual({ type: 'text', text: csv }) + expect(got.data.chars).toBe(csv.length) + } + + const card = await call(headers, 'get_card', { card: ticket }) + expect(card.data.attachments).toEqual([expect.objectContaining({ name: 'session_gap.csv', type: 'text/csv' })]) + }) + + it('cuts a long text file at maxChars and says so', async () => { + await call(headers, 'add_attachment', { card: ticket, filename: 'long.log', text: 'x'.repeat(500) }) + const got = await call(headers, 'get_attachment', { card: ticket, attachment: 'long.log', maxChars: 100 }) + expect(got.content[1]!.text).toHaveLength(100) + expect(got.data).toMatchObject({ truncated: true, returnedChars: 100, chars: 500 }) + }) + + it('attaches base64 and hands an image back as an image block', async () => { + const added = await call(headers, 'add_attachment', { card: ticket, filename: 'pixel.png', base64: PNG_BASE64 }) + expect(added.data.type).toBe('image/png') + const got = await call(headers, 'get_attachment', { card: ticket, attachment: 'pixel.png' }) + expect(got.content[1]).toEqual({ type: 'image', data: PNG_BASE64, mimeType: 'image/png' }) + }) + + it('returns a binary file as details and a link, not as content', async () => { + await call(headers, 'add_attachment', { card: ticket, filename: 'bundle.zip', base64: Buffer.from('PK\u0003\u0004').toString('base64') }) + const got = await call(headers, 'get_attachment', { card: ticket, attachment: 'bundle.zip' }) + expect(got.content).toHaveLength(1) + expect(got.data.url).toMatch(/\/api\/attachments\/[0-9a-f-]+\/download$/) + expect(got.data.note).toContain('download') + }) + + it('carries a file larger than the 1 MB body limit other routes have', async () => { + // Base64 inside JSON-RPC: 2 MB of file is about 2.7 MB of request. + const big = 'a'.repeat(2 * 1024 * 1024) + const added = await call(headers, 'add_attachment', { card: ticket, filename: 'big.txt', base64: Buffer.from(big).toString('base64') }) + expect(added.isError).toBe(false) + expect(added.data.size).toBe(big.length) + }) + + it('refuses what the upload handler refuses, in its words', async () => { + const bad = await call(headers, 'add_attachment', { card: ticket, filename: 'run.exe', base64: 'TVo=' }) + expect(bad.isError).toBe(true) + expect(bad.content[0]!.text).toContain('not allowed') + }) + + it('refuses unusable input before uploading anything', async () => { + for (const [args, message] of [ + [{ filename: 'a.txt' }, 'text'], + [{ filename: 'a.txt', text: 'x', base64: 'eA==' }, 'not both'], + [{ filename: 'a.txt', base64: 'not base64!' }, 'not valid base64'], + [{ filename: '../etc/a.txt', text: 'x' }, 'not a path'] + ] as const) { + const res = await call(headers, 'add_attachment', { card: ticket, ...args }) + expect(res.isError, message).toBe(true) + expect(res.content[0]!.text).toContain(message) + } + }) + + it('deletes by name, and an unknown name lists what the card has', async () => { + await call(headers, 'add_attachment', { card: ticket, filename: 'gone.md', text: '# bye' }) + const del = await call(headers, 'delete_attachment', { card: ticket, attachment: 'gone.md' }) + expect(del.data.deleted.name).toBe('gone.md') + const miss = await call(headers, 'get_attachment', { card: ticket, attachment: 'gone.md' }) + expect(miss.isError).toBe(true) + expect(miss.content[0]!.text).toContain('session_gap.csv') + }) + + it('does not reach another card\'s file by its id', async () => { + const other = await registerTestUser() + const otherHeaders = (await createTestToken(other)).headers + const otherProject = await createTestProject(other, { name: `MCP other ${Date.now()}` }) + const otherTicket = (await call(otherHeaders, 'create_card', { project: otherProject.slug, title: 'Theirs' })).data.ticket + const theirs = await call(otherHeaders, 'add_attachment', { card: otherTicket, filename: 'secret.txt', text: 'secret' }) + const res = await call(headers, 'get_attachment', { card: ticket, attachment: theirs.data.id }) + expect(res.isError).toBe(true) + expect(res.content[0]!.text).not.toContain('secret\n') + }) +})