
    kKj;8                    P   d Z ddlmZ 	 ddlmZmZ ddlmZ ddlm	Z	 ddl
mZmZmZmZmZmZmZmZmZmZmZmZmZmZ ddlmZmZmZ ddlmZmZm Z m!Z! dd
l$Z$ddl%m%Z%m&Z& ddl'm(Z( ddl)m*Z* ddl+m,Z,  e-d      Z.ddZ/ddZ0ddZ1 G d de*      Z2y
# e"$ rZ# e"d	      e#d
Z#[#ww xY w)u,  FileUpload — a Provider that adds drag-and-drop file upload to any server.

Lets users upload files directly to the server through an interactive UI,
bypassing the LLM context window entirely. The LLM can then read and work
with uploaded files through model-visible tools.

Requires ``fastmcp[apps]`` (prefab-ui).

Usage::

    from fastmcp import FastMCP
    from fastmcp.apps import FileUpload

    mcp = FastMCP("My Server")
    mcp.add_provider(FileUpload())

For custom persistence, override the storage methods::

    class S3Upload(FileUpload):
        def on_store(self, files, ctx):
            # write to S3, return summaries
            ...

        def on_list(self, ctx):
            # list from S3
            ...

        def on_read(self, name, ctx):
            # read from S3
            ...
    )annotations)SetState	ShowToast)CallTool)	PrefabApp)H3BadgeButtonCardCardContent
CardFooter
CardHeaderColumnDropZoneMutedRow	SeparatorSmallText)ElseForEachIf)ERRORRESULTSTATERxzHFileUpload requires prefab-ui. Install with: pip install 'fastmcp[apps]'N)datetimetimezone)Any)
FastMCPApp)Context)z.csvz.jsonz.txtz.mdz.pyz.yamlz.ymlz.tomlc                x    t        |       }|dk(  ry| j                  dt        d|dz
              }|dz  dz  |z
  S )zLReturn the exact decoded byte-length of a base64 string without decoding it.r   =         )lencountmax)b64npaddings      i/Users/ahmed/devFolder/Ultron/claude-voice/.venv/lib/python3.12/site-packages/fastmcp/apps/file_upload.py_b64_decoded_sizer.   J   sB    CAAviiSAE]+Gq5A:    c                D    | dk  r|  dS | dk  r	| dz  ddS | dz  ddS )Ni   z Bi   z.1fz KBz MB )sizes    r-   _format_sizer3   S   sF    d{r{		+c"#&&+&s+3//r/   c                B    | d   | d   | d   t        | d         | d   dS )Nnametyper2   uploaded_at)r5   r6   r2   size_displayr7   )r3   )entrys    r-   _make_summaryr:   \   s5    fff$U6]3]+ r/   c                       e Zd ZdZ	 dddddd	 	 	 	 	 	 	 	 	 	 	 d fdZddZdd	Z	 	 	 	 	 	 dd
ZddZddZ	ddZ
 xZS )
FileUploada  A Provider that adds file upload capabilities to a server.

    Registers a drag-and-drop UI tool, a backend storage tool, and
    model-visible tools for listing and reading uploaded files.

    Files are scoped by MCP session and stored in memory by default.
    Override ``on_store``, ``on_list``, and ``on_read`` for custom
    persistence (filesystem, S3, database, etc.). Each method receives
    the current ``Context``, giving access to session ID, auth tokens,
    and request metadata for partitioning and authorization.

    **Session scoping:** The default storage uses ``ctx.session_id`` to
    isolate files by session. This works with stdio, SSE, and stateful
    HTTP transports. In **stateless HTTP** mode, each request creates a
    new session, so files won't persist across requests. For stateless
    deployments, override the storage methods to partition by a stable
    identifier from the auth context::

        class UserScopedUpload(FileUpload):
            def on_store(self, files, ctx):
                user_id = ctx.access_token["sub"]
                ...

    Example::

        from fastmcp import FastMCP
        from fastmcp.apps.file_upload import FileUpload

        mcp = FastMCP("My Server")
        mcp.add_provider(FileUpload())
    i   zFile UploadzsDrop files to upload them to the server. The model can then read and analyze them without using the context window.zDrop files here)max_file_sizetitledescription
drop_labelc                   t         |   |       || _        || _        || _        || _        i | _        | j                          y )N)super__init___max_file_size_title_description_drop_label_store_register_tools)selfr5   r=   r>   r?   r@   	__class__s         r-   rC   zFileUpload.__init__   sF     	+'% =?r/   c                "    d| j                   dS )NzFileUpload())r5   )rJ   s    r-   __repr__zFileUpload.__repr__   s    TYYM++r/   c                :    	 |j                   S # t        $ r Y yw xY w)a  Return the key used to partition file storage.

        Defaults to ``ctx.session_id``, which is stable for stdio, SSE,
        and stateful HTTP. The default ``on_store``/``on_list``/``on_read``
        implementations call this to partition the in-memory store.

        Override to scope by user, tenant, or any other dimension::

            def _get_scope_key(self, ctx):
                return ctx.access_token["sub"]
        __default__)
session_idRuntimeError)rJ   ctxs     r-   _get_scope_keyzFileUpload._get_scope_key   s#    	!>>! 	! 	!s    	c                X   | j                  |      }| j                  j                  |i       }|D ]M  }|d   |d   |d   |d   t        j                  t
        j                        j                  d      d||d   <   O |j                         D cg c]  }t        |       c}S c c}w )at  Store uploaded files and return summaries.

        Args:
            files: List of file dicts, each with ``name``, ``size``,
                ``type``, and ``data`` (base64-encoded content).
            ctx: The current request context. Use for session ID,
                auth tokens, or any metadata needed for partitioning.

        Override this method for custom persistence. The default
        implementation stores files in memory, scoped by
        ``_get_scope_key(ctx)``.

        Returns:
            List of file summary dicts (``name``, ``type``, ``size``,
            ``size_display``, ``uploaded_at``).
        r5   r2   r6   dataseconds)timespec)r5   r2   r6   rV   r7   )
rT   rH   
setdefaultr   nowr   utc	isoformatvaluesr:   )rJ   filesrS   scopesession_filesfes          r-   on_storezFileUpload.on_store   s    * ##C(..ub9A&	&	&	&	'||HLL9CCYCW(M!F)$  +8*>*>*@A*@Qa *@AAAs   B'c                    | j                  |      }| j                  j                  |i       }|j                         D cg c]  }t	        |       c}S c c}w )a  List all stored files.

        Args:
            ctx: The current request context.

        Override this method for custom persistence. The default
        implementation returns files from the current scope.

        Returns:
            List of file summary dicts.
        )rT   rH   getr]   r:   )rJ   rS   r_   r`   rb   s        r-   on_listzFileUpload.on_list   sP     ##C(r2*7*>*>*@A*@Qa *@AAAs    Ac                    | j                  |      }| j                  j                  |i       }||vr*t        |j	                               }t        d|d|       ||   d   d   d   d   d}d   j                  d      xs t        fd	t        D              }|r-	 t        j                  d
         j                  d      |d<   |S d
   dd dz   |d<   |S # t        $ r d
   dd dz   |d<   Y |S w xY w)a>  Read a file's contents by name.

        Args:
            name: The filename to read.
            ctx: The current request context.

        Override this method for custom persistence. The default
        implementation reads from the current scope's in-memory store.
        Text files are decoded from base64; binary files return a
        truncated base64 preview.

        Returns:
            Dict with file metadata and ``content`` (text) or
            ``content_base64`` (binary preview).

        Raises:
            ValueError: If the file is not found.
        File z not found. Available: r5   r2   r6   r7   )r5   r2   r6   r7   ztext/c              3  F   K   | ]  }d    j                  |        yw)r5   N)endswith).0extr9   s     r-   	<genexpr>z%FileUpload.on_read.<locals>.<genexpr>  s%      ;
3CCE&M""3'3Cs   !rV   zutf-8contentN   z...content_base64)rT   rH   re   listkeys
ValueError
startswithany_TEXT_EXTENSIONSbase64	b64decodedecodeUnicodeDecodeError)	rJ   r5   rS   r_   r`   	availableresultis_textr9   s	           @r-   on_readzFileUpload.on_read   sG   & ##C(r2}$]//12IuTH,CI;OPPd#&M&M&M /	"
 -**73 
s ;
3C;
 8
 G$*$4$4U6]$C$J$J7$Sy!
  (-V}Tc':U'BF#$	 & G+0=#+>+F'( 	Gs   &*C" "C=<C=c                    | | j                         dfd       }| j                  d      dfd       }| j                  d      d	fd       }| j                         d
fd       }y )Nc                   | D ]m  }t        |j                  dd            }|j                  kD  s.t        d|j                  dd      dt	        |       dt	        j                         d       j                  | |      S )	zQStore uploaded files. Receives file objects with name, size, type, data (base64).rV    rh   r5   ?z exceeds max size (z > rM   )r.   re   rD   rs   r3   rc   )r^   rS   ra   actual_sizeproviders       r-   store_filesz/FileUpload._register_tools.<locals>.store_files  s      0fb0AB!8!88$fc 25 6(56c'(?(?@AD   $$UC00r/   T)modelc                &    j                  |       S )z&List all uploaded files with metadata.)rf   )rS   r   s    r-   
list_filesz.FileUpload._register_tools.<locals>.list_files)  s     ##C((r/   c                (    j                  | |      S )z)Read an uploaded file's contents by name.)r~   )r5   rS   r   s     r-   	read_filez-FileUpload._register_tools.<locals>.read_file.  s     ##D#..r/   c                $
   t        d      5 }t               5  t        dd      5  t        j                         t        t        j                  j                               5  t        t        j                  j                         d       ddd       ddd       ddd       t               5  t        d	
      5  t        j                         t        ddj                  dt!        j"                         dj"                         t        t        j$                  j                               5  t        d
      5  t'        d      5  t        dd      5  t        d
      5  t)        t+        d             t        t+        d             ddd       ddd       ddd       t-        dt/        ddt+        d      it1        dt2              t1        dg       t5        dd      gt5        t6        d                   ddd       ddd       t        t        j                  j                               5  t9                t;        dd       t'        d      5 }t        ddd      5  t        d
      5  t)        |j<                         t        |j>                         ddd       t        d
      5  t        |j@                  d       t        |jB                  d        ddd       ddd       ddd       ddd       ddd       ddd       tE               5  t        dd!"      5  t        t        j                  j                               5  t        t        j                  j                          d#t        j                  j                         jG                  d$       d%       ddd       tI               5  t        d&       ddd       ddd       ddd       ddd       tK        g jM                  |       d'(      S # 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   ZxY w# 1 sw Y   _xY w# 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   "xY w# 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y   xY w# 1 sw Y    xY w))zDUpload and manage files. Drop files here to send them to the server.zmax-w-2xl mx-auto)	css_classr$   center)gapalign	secondary)variantNr&   )r   pendinginboxzAny file type, up to T)r5   iconlabelr?   multiplemax_sizer   z
$item.namez
$item.typezUpload to Serverr   r^   storedzFiles uploaded!successerror)	arguments
on_successon_error)on_clickUploadedzfont-medium text-smzjustify-between)r   r   r   outlinezw-full)r   r    filez
 on serverzNo files uploaded yet)r   r   )viewstate)'r   r   r   r   rE   r   r   r   lengthr	   r   r   r   rF   r   rG   r3   rD   r   r   r   r   r
   r   r   r   r   r   r   r   r5   r7   r6   r8   r   	pluralizer   r   rf   )rS   r   ra   r   s      r-   file_managerz0FileUpload._register_tools.<locals>.file_manager3  s     34\31H#=x'ELL//12!LL//1$/ 3 $>\ !]FqM(//0&$&223+H,C,CDEG "&!)!8!8
 EMM0023V]#I.AX6"qM!"\"23!"\"23 * 7 / .%- -$+R	]+" %-Xv$>$,Y$;$-(909%&," *3$),3*"& 6C3> ELL//12!&&;
 $H-$%&.*; "(A %aff %amm 4 "/ "% %affk B %$%NN,5!" ", . 3] %2]L  \3X#JELL//12$||2245 3 3 5 ? ? GH() 3 56   $K\_ 5r !&..s3 m 32 $>#=\\6 *M 76 /. 6C]33Z "/ ",  .- 32] %2M]]N 32   $K#J\\_ 54s  TP(=P$*P	PP(T0S=A8R75Q)	QQQ))P5QQ"A"QQ)	/R7;#R*	R-R:+Q6%R9/R(R0R8R*	 R7ST"S80(S+AS	1S+S	S+S8TPPP% P((P2	-T5P?:QQQQQQ&!Q)	)Q3.R76R ;RRRRRR'"R*	*R4/R77S<SS		TSS+S(#S++S50S88T	=TT)r^   
list[dict]rS   r!   returnr   )rS   r!   r   r   )r5   strrS   r!   r   dict)rS   r!   r   r   )toolui)rJ   r   r   r   r   r   s        @r-   rI   zFileUpload._register_tools  sz    		1 
	1 
		) 
	) 
		/ 
	/ 
a	 
a	r/   )Files)r5   r   r=   intr>   r   r?   r   r@   r   r   None)r   r   )rS   r!   r   r   )r^   list[dict[str, Any]]rS   r!   r   r   )rS   r!   r   r   )r5   r   rS   r!   r   dict[str, Any])r   r   )__name__
__module____qualname____doc__rC   rN   rT   rc   rf   r~   rI   __classcell__)rK   s   @r-   r<   r<   f   s    D  ."0 , 	
    
0,!"B#B B 
	BBB )^~r/   r<   )r*   r   r   r   )r2   r   r   r   )r9   r   r   r   )3r   
__future__r   prefab_ui.actionsr   r   prefab_ui.actions.mcpr   prefab_ui.appr   prefab_ui.componentsr   r	   r
   r   r   r   r   r   r   r   r   r   r   r   !prefab_ui.components.control_flowr   r   r   prefab_ui.rxr   r   r   r   ImportError_excrw   r   r   typingr   fastmcp.apps.appr    fastmcp.server.contextr!   	frozensetrv   r.   r3   r:   r<   r1   r/   r-   <module>r      s   @ #5.'     DC55  '  ' *E 
 0o o[  
Rs   A
B B%	B  B%